Handling drop-downs in Selenium WebDriver


In this tutorial, we are going to study the handling of dropdowns in Selenium WebDriver. For practicing, you can check the dummy page having a dropdown element.

Dropdown in selenium

.

Select in Selenium WebDriver

The 'Select' class in Selenium WebDriver is used for selecting and deselecting option in a dropdown. The objects of Select type can be initialized by passing the dropdown webElement as parameter to its constructor.

WebElement testDropDown = driver.findElement(By.id("testingDropdown"));
Select dropdown = new Select(testDropDown);

Selecting options from dropdown

There are three ways of selecting options from dropdown-

  1. selectByIndex - To select an option based on its index, beginning with 0.
    dropdown.selectByIndex(3);
    

  2. selectByValue - To select an option based on its 'value' attribute.
    dropdown.selectByValue("Database");
    

  3. selectByVisibleText - To select an option based on the text over the option.
    dropdown.selectByVisibleText("Database Testing");
    

Different utility methods in the Select class

  • deselectAll() - To deselect all the selected options.
  • deselectByIndex(int index) - To deselect the option based on its index.
  • deselectByValue(String valueAttribute) - To deselect the option its 'value' attribute.
  • deselectByVisibleText(String text) - To deselect the option based on the text over the option.
  • getOptions() - To return list of all the options(List<WebElement>).
  • getAllSelectedOptions() - To return the list of all the selected options(List<WebElement>).
  • getFirstSelectedOption() - To return the selected option or the first selected option in case of dropdowns allowing multi-select.
  • isMultiple() - To return a boolean value, checking if the dropdown allows multiple option select or not.

Reference-

Documentation for Select Class in SeleniumHQ Github