How to get all options from a dropdown in Selenium WebDriver

In order to get all options from a dropdown in Selenium WebDriver, we can utilize the same Select class, which we use to select a value in the dropdown. Check How to select a dropdown using Selenium to understand it more.

Apart from other methods, the Select class also provides a method called getOptions. This getOptions method returns all the options from the dropdown which are defined in <option> tag of the HTML dom for that specific dropdown. These options are returned in a List.

We can further perform operations such as finding the size of the list to check the total number of options available in the dropdown.

Example code to get all options from a dropdown in Selenium
  /** 
     * 
     * This method reads all the options from a selec
     * @param driver
     * @param selectXpath xpath of the select element 
    */
    public static void getDropdownOptions(WebDriver driver, String selectXpath) {
        String[] alloptions;
        String option;
        Select s = new Select(driver.findElement(By.xpath(selectXpath)));
        List listOptions = s.getOptions();
        int size = listOptions.size();
        for (int i = 0; i < size; i++) {
            option = listOptions.get(i).getText();
            System.out.println(option);
        }
    }

You may also read

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.