如何在 Java 中使用 HtmlUnit 从下拉框中选择一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4865761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:23:46  来源:igfitidea点击:

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

javahtmlunit

提问by Peter

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

我在 Java 中使用 HtmlUnit 导航到网页。从那个网页我需要登录然后从那里去。我知道如何输入用户名和密码,但是有一个下拉框,我需要在其中选择一个选项。如何从 HtmlUnit 的下拉框中选择一个选项?谢谢

回答by skaffman

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

您可以<select>使用HtmlSelect以下方法导航和操作页面元素:

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

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

JavaDoc中显示,有很多做这样的事情灵活的API方法。

回答by George

Following code:

以下代码:

HtmlSelect select = page.getElementById(mySelectId);

should be:

应该:

HtmlSelect select = (HtmlSelect)page.getElementById(mySelectId);

回答by Orod Semsarzadeh

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