如何使用带有 Java 的 Selenium WebDriver 从下拉列表中选择一个选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14645045/
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
How to select an option from a drop-down using Selenium WebDriver with Java?
提问by koganti purna chandra sekhar
I need to select a category from the below html. I tried different options, and different ways showed in the blogs, but not able to select the options. Any help will be appreciated.
我需要从下面的 html 中选择一个类别。我尝试了不同的选项,博客中显示了不同的方式,但无法选择选项。任何帮助将不胜感激。
One way I am using as (Not a better one)
我使用的一种方式(不是更好的方式)
private boolean select_dropdown_xpath(String value, String seleniumObjectValue) {
try {
boolean isListItemFound = false;
int i = 0;
do {
i++;
String category = driver.findElement(By.xpath(seleniumObjectValue+"/div["+ i +"]")).getText();
if(category.equals(value)) {
driver.findElement(By.xpath(seleniumObjectValue+"/div["+ i +"]")).click();
isListItemFound = true;
}
} while (isListItemFound == false);
if(!(isListItemFound)) {
return false;
}
} catch(Exception e) {
return false;
}
return true;
}
Tool: Selenium WebDriver 2.28 with Java
工具:带有 Java 的 Selenium WebDriver 2.28
Thanks Purna
谢谢普尔纳
HTML:
HTML:
<div class="drop-down">
<div class="label_field">
<label>Category:</label>
<fieldset>
<div id="Ccategory" class="jSym_select_element jSym_pie jSym_noSelectText false hover" tabindex="0" textval="Default" style="width: 350px;">
<div class="jSym_drop_arrow false"/>
<div class="jSym_select_inner false">Default</div>
</div>
<div id="selectDrop" class="jSym_select_drop jSym_noSelectText " style="height: 50px; width: 350px; margin-top: 10px;">
<div class="jSym_select_item jSym_noSelectText" optionval="Default">Default</div>
<div class="jSym_select_item jSym_noSelectText" optionval="Reset">Reset</div>
</div>
<select id="select_category" class="jSym_dropdown" name="category" style="visibility: hidden;">
<option value="Default">Default</option>
<option value="Reset">Reset</option>
</select>
</fieldset>
</div>
</div>
回答by Manigandan
Try this code:
试试这个代码:
Select sele = new Select(driver.findElement(By.id("select_category")));
//Select the dropdown by using the displayed value.
sele.selectByVisibleText(`displayed value`);
//or you can Select the dropdown by using the index value.
sele.selectByIndex(`index value`);
//or you can Select the dropdown by using the value attribute.
sele.selectByIndex(`value in the value attribute`);
In your case the dropdown visibility is hidden. So, first make it as visible by using JavaScript Executor
class. Then use the above code.
在您的情况下,下拉可见性是隐藏的。因此,首先使用JavaScript Executor
class使其可见。然后使用上面的代码。