Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (62.9k 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.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...