How to get the selected value from the drop-down list using Selenium WebDriver (Selenium 2)?

Suppose I have this HTML code:

<select id="superior" size="1" name="superior"> <option value=""></option> <option value="ciemmd.Division_1">DIVISION007</option> <option selected="selected" value="ciemmd.Division_$$_javassist_162_119">MyDivision</option> <option value="ciemmd.Division_121">MyDivision4</option> <option value="ciemmd.Division_122">MyDivision5</option> </select> 

So this is a combo box

 id=superior 

and MyDivision is currently selected.

Using Selenium WebDriver I am trying to get the selected value, but have not succeeded.

I tried:

 String option = this.ebtamTester.firefox.findElement(By.id(superiorId)).getText(); return option; 

But this returns me all the values ​​in the combo box.

Help me please?

Edit:

 WebElement comboBox = ebtamTester.firefox.findElement(By.id("superior")); SelectElement selectedValue = new SelectElement(comboBox); String wantedText = selectedValue.getValue(); 
+7
source share
5 answers

It is written in C #, but it is not difficult to translate it into any other language that you use:

 IWebElement comboBox = driver.FindElement(By.Id("superior")); SelectElement selectedValue = new SelectElement(comboBox); string wantedText = selectedValue.SelectedOption.Text; 

SelectElement requires you to use OpenQA.Selenium.Support.UI, so at the top enter

 using OpenQA.Selenium.Support.UI; 

Edit:

I suggest that instead of a β€œdriver” you would use

 IWebElement comboBox = this.ebtamTester.firefox.FindElement(By.Id("superior")); 
+14
source

In Java, the following code should work well:

 import org.openqa.selenium.support.ui.Select; Select comboBox = new Select(driver.findElement(By.id("superior"))); String selectedComboValue = comboBox.getFirstSelectedOption().getText(); System.out.println("Selected combo value: " + selectedComboValue); 

Since MyDivision is currently selected, the above code will print "MyDivision"

+9
source

selectedValue.SelectedOption.Text; You will get the text of the selected item. Does anyone know how to get the selected value.

To get the selected value, use

 selectedValue.SelectedOption.GetAttribute("value"); 
+4
source

To select a label-based option:

 Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down"))); select.deselectAll(); select.selectByVisibleText("Value1"); 

To get the first selected value:

 WebElement option = select.getFirstSelectedOption() 
+3
source

Using XPath in C #

  string selectedValue=driver.FindElement(By.Id("superior")).FindElements(By.XPath("./option[@selected]"))[0].Text; 
+2
source

All Articles