Handling dropdowns in selenium webdriver

Handling drop-downs in Selenium WebDriver

Last updated on

In this tutorial, we are going to study the handling of dropdown 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 the 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 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");

Select in Selenium – Utility methods

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, check if the dropdown allows multiple options to select or not.

That’s all we have in this article on Dropdwon in Selenium. If you have any questions please comment below. Also, check out the complete tutorial below.

Complete Step-by-Step Selenium Tutorial

4 thoughts on “Handling drop-downs in Selenium WebDriver”

  1. driver.get(“https://artoftesting.com/samplesiteforselenium”);
    WebElement testDropDown = driver.findElement(By.id(“testingDropdown”));
    Select dropdown = new Select(testDropDown);
    //dropdown.selectByIndex(2);
    dropdown.selectByVisibleText(“Manual Testing”);

    Here is the code I tried. I could get to open the website but not the dropdownlist selection. could you guide me as of where I went wrong.

    Reply

Leave a Comment