java the without - How to select/get drop down option in Selenium 2

4 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")));

To get the first selected value:

WebElement option = select.getFirstSelectedOption()
handle using

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:"//path_to_drop_down", "Value1");

in ruby for constantly using, add follow:

module Selenium
  module WebDriver
    class Element
      def select(value)
        self.find_elements(:tag_name => "option").find do |option|
          if option.text == value

and you will be able to select value:

browser.find_element(:xpath, ".//xpath").select("Value")

A similar option to what was posted above by janderson would be so simply use the .GetAttribute method in selenium 2. Using this, you can grab any item that has a specific value or label that you are looking for. This can be used to determine if an element has a label, style, value, etc. A common way to do this is to loop through the items in the drop down until you find the one that you want and select it. In C#

int items = driver.FindElement(By.XPath("//path_to_drop_Down")).Count(); 
for(int i = 1; i <= items; i++)
    string value = driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).GetAttribute("Value1");
        //Clicked on the index of the that has your label / value

This method will return the selected value for the drop down,

public static String getSelected_visibleText(WebDriver driver, String elementType, String value)
    WebElement element = Webelement_Finder.webElement_Finder(driver, elementType, value);
   Select Selector = new Select(element);
    String textval=Selector.getFirstSelectedOption().getText();
    return textval;


String textval=Selector.getFirstSelectedOption();


Will return all the elements in the drop down.