0 votes
1 view
in Devops and Agile by (19.7k points)

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?

1 Answer

0 votes
by (63.3k points)

Using getText() to be able to get the text, for the option element you have to use getFirstSelectedOption() method as shown below:

 Select select = new Select(driver.findElement(By.xpath("//select")));

WebElement option = select.getFirstSelectedOption();

String defaultItem = option.getText();

System.out.println(defaultItem );

I hope it helps!

For more related queries, you may visit the Selenium interview question page or you can join Selenium certification course for more knowledge.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !