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

12

8

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.

Antipyretic answered 27/5, 2013 at 7:28 Comment(2)
can you paste html code of itLearned
This might be useful to you. [#9563353 [1]: #9563353Gravesend
D
11

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.

Dendro answered 27/5, 2013 at 19:26 Comment(1)
This is good. Thank you. is There a way to get the values of each option?Bushweller
R
9

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());

    }
Rainwater answered 23/7, 2015 at 18:14 Comment(0)
A
0

Namita,

with below code you will get list of options available in select box and you click on one.

List options = select.findElements(By.tagName("option"));

    for(WebElement option : options){
        if(option.getText().equals("male")) {
            option.click();
            break;
        }
    }
Ariannearianrhod answered 27/5, 2013 at 12:2 Comment(0)
N
0

Use this hope it will helpful to you.

List WebElement allSuggestions = driver.findElements(By.xpath("Your Xpath"));      
        for (WebElement suggestion : allSuggestions)
     {
        System.out.println(suggestion.getText());

        }
Niello answered 28/5, 2013 at 10:37 Comment(0)
A
0
List<WebElement> featureList;

featureList = Locate your Element;

for (WebElement i : featureList) {              
System.out.println("\n**********************  " + i.getText());
}
Abshire answered 19/9, 2017 at 9:43 Comment(1)
Why should the OP try this? Good answers will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer.Morea
P
0
WebElement ele=driver.findElement(By.xpath(".//*[@id='month']"));
        List<WebElement> x = ele.findElements(By.tagName("option"));
        for(WebElement ele1:x) {
            String y=ele1.getAttribute("innerHTML");
            System.out.println(y);
        }
Pallet answered 21/2, 2018 at 5:55 Comment(1)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Unaesthetic
I
0
String [] ex = {"A","b","c","d"};

List<WebElement> Str  = driver.findElements(By.xpath("//*[@id=\"institutionName\"]/option"));

for (int i = 0; i < ex.length; i++) {
    System.out.println(Str.get(i).getText());  
    Assert.assertEquals(ex[i], Str.get(i).getText());
}
Itinerancy answered 17/9, 2019 at 6:21 Comment(0)
T
0
Select drop = new Select(driver.findElement(By.id("id")));

List<WebElement> dd = drop.getOptions();

System.out.println(dd.size());

for (int j = 0; j < dd.size(); j++) {
    System.out.println(dd.get(j).getText());

}
Throughput answered 22/11, 2019 at 7:15 Comment(2)
Please add some details around your answer.Mustard
Any description?Ule
C
0

Here is a method to get all dropdowns and return in list.

    public List getDropDownList(String Xpath) {
    WebElement dropdowns = driver.findElement(By.xpath(Xpath));
    Select select = new Select(dropdowns);
    List<String> dropdown = new ArrayList<String>();
    List<WebElement> allOptions = select.getAllSelectedOptions();
    Iterator<WebElement> itr = allOptions.iterator();
    while (itr.hasNext()) {
        String st = itr.next().getText();
        dropdown.add(st);
     }
    return dropdown;
   }

Hope it will help you.

Celestial answered 28/11, 2019 at 13:37 Comment(0)
I
0

I took Facebook's registration page as an example it may help to understand.

Here is a code to get all month's names option as a list from the month's dropdown list.

List<WebElement> option = driver.findElements((By.xpath("//[@id='month']/option")));

ArrayList a = new ArrayList();

        for (WebElement str: option)
        {
           String s =  str.getText();
           if(!s.equals("Month")) {
               a.add(s);
         }
           else {
               continue;
           }
        }

System.out.println("The Output is: "+ a);

Explanation of the above code is,

  1. Storing all the elements in a list.
  2. Declaring an empty Array list for storing options.
  3. By using for each loop to extract all the options one by one and store into the ArrayList.
  4. Printing all options as a list.

Hope this will help you.! Best Luck.!!

Isodimorphism answered 3/2, 2020 at 9:48 Comment(0)
D
0

There are multiple approaches to print the texts from the option elements of a . Ideally while interacting with a element you need to use the Select Class. Further to interact with the <option> tags you need to use getOptions() method.


Demonstration

As an example to print the texts from the Day, Month and Year option elements within landing page https://www.facebook.com/ you need to induce WebDriverWait for the elementToBeClickable() and you can use the following Locator Strategies.


Options from Day Dropdown

Using id attribute:

  • Code Block:

    WebElement dayElement = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("day")));
    Select selectDay = new Select(dayElement);
    List<WebElement> dayList = selectDay.getOptions();
    for (int i=0; i<dayList.size(); i++)
        System.out.println(dayList.get(i).getText());
    

Options from Month Dropdown

Using and stream() and map():

  • Code Block:

    Select selectMonth = new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//select[@id='month']"))));
    List<String> myMonths = selectMonth.getOptions().stream().map(element->element.getText()).collect(Collectors.toList());
    System.out.println(myMonths);
    
  • Console Output:

    [Month, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sept, Oct, Nov, Dec]
    

Options from Year Dropdown using a single line of code

Using [tag:css_selectors] and stream() and map() in a single line of code:

  • Line of code:

    System.out.println(new Select(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("select#year")))).getOptions().stream().map(element->element.getText()).collect(Collectors.toList()));
    
  • Console Output:

    [Year, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995, 1994, 1993, 1992, 1991, 1990, 1989, 1988, 1987, 1986, 1985, 1984, 1983, 1982, 1981, 1980, 1979, 1978, 1977, 1976, 1975, 1974, 1973, 1972, 1971, 1970, 1969, 1968, 1967, 1966, 1965, 1964, 1963, 1962, 1961, 1960, 1959, 1958, 1957, 1956, 1955, 1954, 1953, 1952, 1951, 1950, 1949, 1948, 1947, 1946, 1945, 1944, 1943, 1942, 1941, 1940, 1939, 1938, 1937, 1936, 1935, 1934, 1933, 1932, 1931, 1930, 1929, 1928, 1927, 1926, 1925, 1924, 1923, 1922, 1921, 1920, 1919, 1918, 1917, 1916, 1915, 1914, 1913, 1912, 1911, 1910, 1909, 1908, 1907, 1906, 1905]
    
Dewayne answered 25/7, 2020 at 21:20 Comment(0)
Z
0

//Identify the dropdown

Select sel = new Select(driver.findElement(By.xpath("//div/input"));

//Get list of all options in the dropdown

List lst = sel.getOptions();

//To get text value of all dropdown values

List textValues = sel.getOptions().stream().map(WebElement::getText).collect(Collectors.toList());

Zenger answered 10/11, 2022 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.