如何找到下拉列表的选定选项?

时间:2012-09-27 12:10:37

标签: java selenium webdriver selenium-webdriver

我们如何在Selenium Webdriver中找到Dropdown的选定选项?

我试过了 -

WebElement element = driver.findElement(By.xpath(locator1));
Select select = new Select(element);
List<WebElement> SO = select.getAllSelectedOptions();
String S = SO.toString();
System.out.println(S);

返回WebElements,如 -

[[[[[FirefoxDriver: firefox on XP (c388e8a8-09d5-41b9-b086-0278c639d8b1)] -> xpath: .//*[@id='city']]] -> tag name: option]]

我想找到所选的选项吗?

1 个答案:

答案 0 :(得分:5)

您可以使用getFirstSelectedOption()对象上的Select方法来解析所选元素,您可以通过getText()方法获取该文本。见下面的例子:

单选:

WebElement element = driver.findElement(By.xpath(locator1));
Select select = new Select(element);
WebElement selectedOption = select.getFirstSelectedOption();
System.out.println(selectedOption.getText());

进行多项选择:

WebElement element = driver.findElement(By.xpath(locator1));
Select select = new Select(element);
List<WebElement> selectedOptions = select.getAllSelectedOptions();
for(WebElement selectedOption : selectedOptions) {
    System.out.println(selectedOption.getText());
}