Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all elements from drop down list in Selenium WebDriver?

How can I get all elements from a drop down list? I used the code below:

List<WebElement> elements = driver.findElements(By.id("s"));

But I am always getting the first element only.

like image 639
Namitha Avatar asked May 27 '13 07:05

Namitha


People also ask

How do you get all the values from drop down list in Selenium?

Select select = new Select(driver. findElement(By.id("oldSelectMenu"))); // Get all the options of the dropdown List<WebElement> options = select. getOptions(); Using this method, we can retrieve all the options of a dropdown (be it single-select or multi-select ).

How do you get the text value from the drop down in Selenium?

We can get a selected option in a dropdown in Selenium webdriver. The method getFirstSelectedOption() returns the selected option in the dropdown. Once the option is fetched we can apply getText() method to fetch the text.

How can get xpath for dropdown value?

To get an XPATH of an element right-click the Dropdown menu and select 'Inspect element with Firebug'. Then corresponding code would be highlighted in the firebug, right-click on it and select copy XPath. By this method we can copy the XPATH and paste it into the Selenium IDE tool's Target section.


2 Answers

There is a class designed for this in the bindigs.

You are looking for the Select class:

https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/support/ui/Select.java

You would need to 'find' the actual select element, not the individual options. Find that select element, and let Selenium & the Select class do the rest of the work for you.

You'd be looking for something like (s being the actual select element):

WebElement selectElement = driver.findElement(By.id("s");
Select select = new Select(selectElement);

The Select class has a handy getOptions() method. This will do exactly what you think it does.

List<WebElement> allOptions = select.getOptions();

Now you can do what you want with allOptions.

like image 80
Arran Avatar answered Sep 21 '22 12:09

Arran


This will help to list all the elements from the dropdown:

    Select dropdown = new Select(driver.findElement(By.id("id")));

    //Get all options
    List<WebElement> dd = dropdown.getOptions();

    //Get the length
    System.out.println(dd.size());

    // Loop to print one by one
    for (int j = 0; j < dd.size(); j++) {
        System.out.println(dd.get(j).getText());

    }
like image 38
ISGovind Avatar answered Sep 22 '22 12:09

ISGovind