In this tutorial, we are going to study the handling of dropdowns in Selenium WebDriver. For practice, you can check the dummy page having a dropdown element.
Select in Selenium WebDriver
The ‘Select’ class in Selenium WebDriver is used for selecting and deselecting the option in a dropdown. The objects of Select type can be initialized by passing the dropdown webElement as a parameter to its constructor.
WebElement testDropDown = driver.findElement(By.id("testingDropdown")); Select dropdown = new Select(testDropDown);
Selecting options from the dropdown
There are three ways of selecting options from the dropdown-
- selectByIndex – To select an option based on its index, beginning with 0.
dropdown.selectByIndex(3);
- selectByValue – To select an option based on its ‘value’ attribute.
dropdown.selectByValue("Database");
- 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.