Reputation: 3394
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?
Upvotes: 0
Views: 4300
Reputation: 10402
You can use the getFirstSelectedOption()
method on your Select
object to resolve the selected element and you can get it's text by the getText()
method. See example below:
For single selection:
WebElement element = driver.findElement(By.xpath(locator1));
Select select = new Select(element);
WebElement selectedOption = select.getFirstSelectedOption();
System.out.println(selectedOption.getText());
For multiple selection:
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());
}
Upvotes: 5