How to select a dropdown using selenium web driver

In this article, we are going to learn about how to select a drop down using selenium webdriver. In our selenium automation, we may come across situations like entering text, selecting radio buttons and check boxes etc. Like this way, selenium handles dropdowns in an easy manner.

Points to remember:

Using selenium web driver, we can

  • Select a dropdown
  • Deselect a dropdown
  • Select more than one options if it a multi select.

Syntax:

Select select = new Select(driver.findElement(By.id(“drop1”)));

Select methods:

Select select = new Select(driver.findElement(By.id(“drop1”)));

// selects the dropdown value based on it index value. Usually index value starts from ‘0’. So if you choose index(1), web driver selects the 2nd value of the dropdown.
select.selectByIndex(3);

// selects the option based on the value attribute.
select.selectByValue(“value”);

// select the option based on the visible text present for the option.
select.selectByVisibleText(“visibleText”);

Deselect methods:

Select deselect = new Select(driver.findElement(By.xpath(“//*[contains(@id,’elem xpath’)]”)));

// deselects the dropdown optionbased on it index value. Usually index value starts from ‘0’. So if you choose index(1), web driver deselects the 2nd value of the dropdown.

deselect.deselectByIndex(1);

// deselects the option based on the value attribute.
deselect.deselectByValue(“value”);

// deselect the option based on the visible text present for the option.
deselect.deselectByVisibleText(“visibleText”);

// It is used for multi select dropdown. Below method deselects all the options present in the dropdown.
deselect.deselectAll();

isMultiple(): boolean:

This method is used to find out whether a dropdown allows more than one values to select or not and returns TRUE else returns FALSE. If it returns TRUE, we can select more than one option in normal way i.e,

select.selectByValue(“value1”);

select.selectByValue(“value2”);