How to select dropdown in Selenium using the Select class

In any web-based application, drop-downs are used to help the end user to select a value from a set of predefined values. e.g. Selecting a country from the list of countries.

Selenium has a special class dedicated to operations related to dropdowns. i.e. Select class.

We can use the Select class in selenium to select dropdown in selenium i.e. select a value from the dropdown, get values from the dropdown, etc.

In order to work with this class, we need to import it in our code like below.

Example code to select dropdown in Selenium
/**
 * This method selects a value in dropdown.
 * 
 * @param objSelect Dropdown element
 * @param strValueToSelect String value to select
 */

public static void selectDropDown(WebElement objSelect, String strValueToSelect) {
    try {
        Select dropdown = new Select(objSelect);
        if (dropdown.getOptions().toString().contains(strValueToSelect) == true) {
            dropdown.selectByVisibleText(strValueToSelect);
        } else {
            dropdown.selectByValue(strValueToSelect);
        }

    } catch (Exception e) {

    }

}

You may also read

Similar Posts

2 Comments

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.