0

How do we find the selected option of a Dropdown in Selenium Webdriver??

I tried -

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

which returns WebElements like -

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

I want to find the option that is selected?

4

1 回答 1

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());
}
于 2012-09-27T12:21:41.730 回答