Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the selected value from a combobox using Selenium WebDriver (Selenium 2)?

Assume I have this html code:

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

So this is a combo box with

id=superior 

and currently value MyDivision is selected.

Using Selenium WebDriver I am trying to get the selected value, but no success.

I tried:

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

But this returns me all the values in the combobox.

Help please?

Edit:

WebElement comboBox = ebtamTester.firefox.findElement(By.id("superior"));
SelectElement selectedValue = new SelectElement(comboBox);
String wantedText = selectedValue.getValue();
like image 805
Koray Tugay Avatar asked Aug 16 '12 16:08

Koray Tugay


People also ask

What is ContextClick ()?

ContextClick() Right-clicks the mouse at the last known mouse coordinates. ContextClick(IWebElement) Right-clicks the mouse on the specified element.


1 Answers

This is written in C#, but it shouldn't be hard to transition it over to any other language you're using:

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, type

using OpenQA.Selenium.Support.UI;

Edit:

I suppose for you, instead of 'driver' you would use

IWebElement comboBox = this.ebtamTester.firefox.FindElement(By.Id("superior"));
like image 87
Michael Bautista Avatar answered Oct 11 '22 12:10

Michael Bautista