12

I'm trying to use HtmlUnit in Java to log into a website. First i enter the user name then password. After that i need to select an option from a dropdown box. entering the user and password seemed to have worked but when i try to select the item from the drop down box i get errors. Can anyone help me fix this? My code is as follows:

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;


public class homePage {
  public static void main(String[] args) throws Exception {

    final WebClient webClient = new WebClient();
    final HtmlPage page = webClient.getPage("website name here");
    HtmlElement usrname = page.getElementByName("username");
    usrname.click();
    usrname.type("myusername");
    HtmlElement psswrd = page.getElementByName("password");
    psswrd.click();
    psswrd.type("mypassword");
    HtmlSelect select = (HtmlSelect) page.getElementById("cmbProducts");
    HtmlOption option = select.getOptionByValue("ITDirect");
    select.setSelectedAttribute(option, true);
    HtmlElement signin = page.getElementByName("SignIn");
    signin.click();
    System.out.println(page.getTitleText());
    webClient.closeAllWindows();
  }
}
Tyler
  • 21,762
  • 11
  • 61
  • 90
Peter
  • 5,071
  • 24
  • 79
  • 115

2 Answers2

5

Here's code from the unit tests for HTMLunit.

final HtmlSelect select = form.getSelectsByName("select1").get(0);
final List<HtmlOption> expected = new ArrayList<HtmlOption>();
expected.add(select.getOptionByValue("option1"));
expected.add(select.getOptionByValue("option3"));

Notice that they use getSelectsByName not getElementById.

Here's a link to those unit tests so you can see how they prescribe using the API. http://htmlunit.sourceforge.net/xref-test/com/gargoylesoftware/htmlunit/html/HtmlSelectTest.html

Speck
  • 2,259
  • 1
  • 20
  • 29
3

Get the form of the login username and password.

here is an example:

   HtmlPage page3;
   page3 = webClient.getPage("Website");
   HtmlForm loginForm = page3.getFormByName("loginForm");
   HtmlTextInput username = loginForm.getInputByName("NameofUsernameElement");
   HtmlPasswordInput pass = loginForm.getInputByName("NameofPassowordElement");
   HtmlSubmitInput b = loginForm.getInputByValue("LoginButtonValue");

   username.setValueAttribute("Actualy Username");
   pass.setValueAttribute("Actual Password");
   HtmlPage page2;
   page2 = b.click();
Sanath
  • 4,774
  • 10
  • 51
  • 81
EK_AllDay
  • 1,095
  • 2
  • 15
  • 35