How to use HtmlUnit in Java?

Peter picture Peter · Feb 2, 2011 · Viewed 25.9k times · Source

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();
  }
}

Answer

Speck picture Speck · Feb 8, 2011

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