Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select/get drop down option in Selenium 2

I am converting my selenium 1 code to selenium 2 and can't find any easy way to select a label in a drop down menu or get the selected value of a drop down. Do you know how to do that in Selenium 2?

Here are two statements that work in Selenium 1 but not in 2:

browser.select("//path_to_drop_down", "Value1"); browser.getSelectedValue("//path_to_drop_down"); 
like image 452
user786045 Avatar asked Jun 21 '11 18:06

user786045


People also ask

What is the return type of getOptions () method in Dropdowns?

We can extract all the options in a dropdown in Selenium with the help of Select class which has the getOptions() method. This retrieves all the options on a Select tag and returns a list of web elements. This method does not accept any arguments.

How do you select the second option in Selenium?

The 'Select' class in Selenium WebDriver is used for selecting and deselecting the option in a dropdown. The objects of Select type can be initialized by passing the dropdown webElement as parameter to its constructor. selectByIndex – To select an option based on its index, beginning with 0.

How do I select a dropdown value in automation?

A dropdown is represented by <select> tag and the options are represented by <option> tag. To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.


2 Answers

Take a look at the section about filling in forms using webdriver in the selenium documentation and the javadoc for the Select class.

To select an option based on the label:

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() 
like image 142
janderssn Avatar answered Oct 24 '22 17:10

janderssn


driver.findElement(By.id("id_dropdown_menu")).click(); driver.findElement(By.xpath("xpath_from_seleniumIDE")).click(); 
like image 31
thrasher Avatar answered Oct 24 '22 17:10

thrasher