Select value from dropdown using Selenium

Dropdown handle with Select class :

The Select API has one constructor which takes a WebElement as parameter. It provides several methods to use on a dropdown webpage element.

Select select = new Select(WebElement element);

For e.g. we want to display all countries from the Country dropdown from the below site:

We have a 'select' tag here for the country element.

driver.get("https://orangehrm.com/en/30-day-free-trial");
By countryElement = By.id("Form_getForm_Country");
WebElement countryDropdown = driver.findElement(countryElement);
//create a Select class object :
Select select = new Select(countryDropdown);

Useful methods :

getOptions() : This method returns list of web elements i.e. all options available in the dropdown.

//getOptions() returns List<WebElement> :
List<WebElement> countries = select.getOptions();
System.out.println("Number of country options : "+ countries.size());
//It should print 233 -- including the 'country' option in the dropdown

Now, if we expand the select tag, we will see the below DOM structure :

selectByVisibleText(String text): When we want to select an element by its visible text, we can use this method. Here, in the DOM, we have same 'value' and 'innerText' attributes. They both have the country names as their attribute values.

There are scenario where 'value' attribute will have numbers and 'innerText' as the country names as attribute values. There we can easily use the selectByVisibleText() to select an element.

select.selectByVisibleText("Bulgaria"); //It will select Bulgaria in the dropdown field

Let's take another example : https://www.wikipedia.org/ Here, we have a language dropdown. And the DOM structure looks like :

selectByValue(String value) : Here, we can use this method to select a particular language.

select.selectByValue("ar"); //It will select Arabic language from the dropdown

selectByIndex(int index) : We can provide index of the web element we want to select as well.

driver.get("https://www.wikipedia.org/");
WebElement languageSelect = driver.findElement(By.id("searchLanguage"));
select = new Select(languageSelect);
select.selectByIndex(2); //It will select Arabic language from the dropdown

Dropdown handle without Select class :

In this case we can use xpaths for the dropdown and store all options in a list. To select an option, we can iterate through the list as below:

driver.get("https://www.wikipedia.org/");    
List<WebElement> languages = driver.findElements(By.xpath("//select/option"));        
    for(WebElement e : languages) {
        if(e.getAttribute("value").equals("ar")) {
            e.click();
        }
    } //It would select the AR option from the dropdown