1
votes

I'm new to Selenium WebDriver. I'm testing a drop down list. Here is the code I used to select an item from the drop down.

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

This is working fine, but what I need is to get selected item as a text. For an example, under the value = FEM , the text displays is female. I need to get the text as Selected value is female.

I've searched some articles and none of this worked. Please help. :)

3

3 Answers

2
votes

Select has getFirstSelectedOption() method. From there you can use getText()

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

WebElement option = dropdown.getFirstSelectedOption();
String text = option.getText();
2
votes

You can use element1.selectByVisibleText(value); if you want to set the option using text instead of value

If you want to get the value use element1.getAllSelectedOptions().get(0).getText()

or element1.getFirstSelectedOption()

0
votes

instead of using dropdown.selectByvalue("FEM") use dropdown.selectByVisibleText("FEM")