Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HtmlUnit in Java to select an element from a drop down box?

Tags:

I'm using HtmlUnit in Java to navigate to a web page. From that webpage i need to log in and then go from there. I know how to type in the user name and password but then there is a dropdown box where i need to select one of the options. How do i select an option from a dropdown box in HtmlUnit? Thanks

like image 289
Peter Avatar asked Feb 01 '11 17:02

Peter


3 Answers

You can navigate and manipulate the page <select> elements using HtmlSelect:

WebClient client = ...
Page page = client.getPage(url);
HtmlSelect select = (HtmlSelect) page.getElementById(mySelectId);
HtmlOption option = select.getOptionByValue(desiredOptionValue);
select.setSelectedAttribute(option, true);

The JavaDoc shows that there are a lot of flexible API methods for doing things like this.

like image 169
skaffman Avatar answered Oct 07 '22 22:10

skaffman


Add the follwoing lines:

protected void selectOption(WebElement el, String option)
{
    Select select = new Select(el);
    select.selectByVisibleText(option);
}

protected WebElement elById(String id)
{
    return driver.findElement(By.id(id));
}

// "title" is your drop-down HTML id 
public void populateForm(String elValue)
{
    selectOption(elById("title"), elValue);
}
like image 41
Orod Semsarzadeh Avatar answered Oct 07 '22 20:10

Orod Semsarzadeh


Following code:

HtmlSelect select = page.getElementById(mySelectId);

should be:

HtmlSelect select = (HtmlSelect)page.getElementById(mySelectId);
like image 35
George Avatar answered Oct 07 '22 20:10

George