How to select dropdown in Selenium using the Select class

We can use the Select class in selenium to select dropdown in selenium. We can use it to select a value from the dropdown and get values from the dropdown.

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.

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

Related Posts