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

前端 未结 11 2115
遥遥无期
遥遥无期 2020-12-11 06:10

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

List elements = driver.findElements(By.id(\"s\"));
11条回答
  •  被撕碎了的回忆
    2020-12-11 06:27

    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 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.!!

提交回复
热议问题