如何从没有ID或名称的下拉列表中选择值

时间:2014-05-27 15:04:37

标签: selenium-webdriver

无法从selenium Webdriver的下拉列表中选择Value Test3 这是下拉列表的HTML源代码

> <tr><td>Case Categories</td>
<td><select class="chzn-select" multiple="multiple" style="width: 500px" data-placeholder="Select categories..." size="4" name="categories[]" id="categories">
<option value="2">Test1</option>
<option value="3">Test2</option>
<option value="4">Test3</option>
<option value="1">Test</option>
</select></td></tr>
下面的

是为选择值

而编写的selenium代码
`driver.findElement(By.cssSelector("input.default")).click();
driver.findElement(By.cssSelector("a.search-choice-close")).click();`

3 个答案:

答案 0 :(得分:0)

el = driver.find_element_by_id('categories')
for option in el.find_elements_by_tag_name('option'):
    if option.get_attribute("value") == "4":
        option.click()

答案 1 :(得分:0)

请使用以下代码:

Select dropDown = new Select(driver.findElement(By.id("categories")));
dropDown.selectByVisibleText("Test3");

或者

dropDown.selectByValue("4");

答案 2 :(得分:0)

在这里,您可以使用xpath标识元素并对其执行所需的操作

String xpath="//tr/td[2]/select/option[3]";
(or) xpath="//tr/td[2]//option[3]";
driver.findElement(By.xpath(xpath)).click();

你可以使用基于xpaths的不同标准来查找元素,你可以使用xpaths找到任何页面上的大多数元素