简体   繁体   中英

Get selected option using Selenium WebDriver with Java

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. :)

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

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

而不是使用dropdown.selectByvalue("FEM")使用dropdown.selectByVisibleText("FEM")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM