Java – How to get selected option using Selenium WebDriver with Java

javajunit4seleniumselenium-webdriverwebdriver

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?

Best Answer

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