[java] 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");

This question is related to java selenium drop-down-menu selenium-webdriver

The answer is


driver.findElement(By.id("id_dropdown_menu")).click();
driver.findElement(By.xpath("xpath_from_seleniumIDE")).click();

good luck


Try using:

selenium.select("id=items","label=engineering")

or

selenium.select("id=items","index=3")

This is the code to select value from the drop down

The value for selectlocator will be the xpath or name of dropdown box, and for optionLocator will have the value to be selected from the dropdown box.

public static boolean select(final String selectLocator,
        final String optionLocator) {
    try {
        element(selectLocator).clear();
        element(selectLocator).sendKeys(Keys.PAGE_UP);
        for (int k = 0; k <= new Select(element(selectLocator))
                .getOptions().size() - 1; k++) {
            combo1.add(element(selectLocator).getValue());
            element(selectLocator).sendKeys(Keys.ARROW_DOWN);
        }
        if (combo1.contains(optionLocator)) {
            element(selectLocator).clear();
            new Select(element(selectLocator)).selectByValue(optionLocator);
            combocheck = element(selectLocator).getValue();
            combo = "";

            return true;
        } else {
            element(selectLocator).clear();
            combo = "The Value " + optionLocator
                    + " Does Not Exist In The Combobox";
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        errorcontrol.add(e.getMessage());
        return false;
    }
}



private static RenderedWebElement element(final String locator) {
    try {

        return (RenderedWebElement) drivers.findElement(by(locator));
    } catch (Exception e) {
        errorcontrol.add(e.getMessage());
        return (RenderedWebElement) drivers.findElement(by(locator));
    }
}

Thanks,

Rekha.


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");
    if(value.Conatains("Label_I_am_Looking_for"))
    {
        driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).Click(); 
        //Clicked on the index of the that has your label / value
    }
}

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
            option.click
              return
           end
       end
    end
  end
end

and you will be able to select value:

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

you can do like this :

public void selectDropDownValue(String ValueToSelect) 
{

    webelement findDropDownValue=driver.findElements(By.id("id1"))    //this will find that dropdown 

    wait.until(ExpectedConditions.visibilityOf(findDropDownValue));    // wait till that dropdown appear

    super.highlightElement(findDropDownValue);   // highlight that dropdown     

    new Select(findDropDownValue).selectByValue(ValueToSelect);    //select that option which u had passed as argument
}

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);
    Selector.getFirstSelectedOption();
    String textval=Selector.getFirstSelectedOption().getText();
    return textval;
  }

Meanwhile

String textval=Selector.getFirstSelectedOption();

element.getText();

Will return all the elements in the drop down.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java