How to get selected option using Selenium WebDriver with Java

Aditi picture Aditi · Aug 13, 2012 · Viewed 136.7k times · Source

I want to get the selected label or value of a drop down using Selenium WebDriver and then print it on the console.

I am able to select any value from the drop down, but I am not able to retrieve the selected value and print it:

Select select = new 
Select(driver.findElement(By.id("MyDropDown"))).selectByVisibleText(data[11].substring(1 , data[11].length()-1));
WebElement option = select.getFirstSelectedOption();

But all my efforts were in vain. How do I get the selected option?

Answer

Justin Ko picture Justin Ko · Aug 13, 2012

You should be able to get the text using getText() (for the option element you got using getFirstSelectedOption()):

Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );