java 如何使用 WebDriver 单击 <option> 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11343017/
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-31 04:42:10  来源:igfitidea点击:

How to click an <option> element with WebDriver?

javaseleniumwebdriverui-automation

提问by Kiran Koundinya

This is a piece of UI code

这是一段UI代码

<select id="order_unit_line_rate_806782_is_addenda_enabled" class="selects_for_487886" onchange="select_addendum(806782, this);dateShowMemory(this.options[this.selectedIndex].value, '806782');" uniqueattr="Dynamic Site Accelerator / Dynamic Site Accelerator / Additional Usage Commitment / drop down" name="order_unit_line_rate[806782][is_addenda_enabled]">
     <option value="0" uniqueattr="Dynamic Site Accelerator / Dynamic Site Accelerator / Additional Usage Commitment / Fee">                     Fee                   </option>
     <option value="1" uniqueattr="Dynamic Site Accelerator / Dynamic Site Accelerator / Additional Usage Commitment / See Attached Addendum">                     See Attached Addendum                   </option>
</select>

where the <option>tags are nested inside the <select>tag. I need to click()on the second <option>element which is an item in the dropdown list. The dropdown is clickable when i try to click()on the <select>tag using id / uniqueattr.

其中<option>标签嵌套在<select>标签内。我需要click()在第二个<option>元素上,它是下拉列表中的一个项目。当我尝试使用 id / uniqueattrclick()<select>标签上时,下拉菜单是可点击的。

How do I traverse the <option>tags nested under <select>and click on the right item?

如何遍历<option>嵌套在下面的标签<select>并单击正确的项目?

采纳答案by Qwerky

This will select the option with value "1" in the select with id "order_unit_line_rate_806782_is_addenda_enabled".

这将在 ID 为“order_unit_line_rate_806782_is_addenda_enabled”的选择中选择值为“1”的选项。

Select select = (Select)webdriver.findElement(By.id("your id here"));
select.selectByValue("1");

You can also select by index or text; see the docs.

也可以按索引或文本选择;请参阅文档

回答by Petr Jane?ek

Besides the correct Qwerky's answer, you can also do simple

除了正确的 Qwerky 的答案,你还可以做简单的

driver.findElement(By.xpath("//select/option[@value='1']")).click();

This finds the optionelement with value='1'and clicks it, practically selecting it in the drop-down.

这会找到option元素value='1'并单击它,实际上是在下拉列表中选择它。

Both mine and Qwerky's solution are described and explained here, in the documentation.

我的和 Qwerky 的解决方案都在文档中进行了描述和解释