</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How to handle dropdowns in Selenium WebDriver?

Answer

Use the Select class from org.openqa.selenium.support.ui.Select to handle standard HTML <select> dropdowns.

Setup:

Java
import org.openqa.selenium.support.ui.Select;

WebElement dropdown = driver.findElement(By.id("countrySelect"));
Select select = new Select(dropdown);

3 ways to select an option:

Java
select.selectByVisibleText("India");
select.selectByValue("IN");
select.selectByIndex(2);

Get selected value:

Java
String selected = select.getFirstSelectedOption().getText();
System.out.println("Selected: " + selected);

Get all options:

Java
List<WebElement> options = select.getOptions();
for (WebElement option : options) {
    System.out.println(option.getText());
}

Multi-select dropdowns:

Java
if (select.isMultiple()) {
    select.selectByVisibleText("India");
    select.selectByVisibleText("USA");
    select.deselectAll();
}

Note: The Select class only works with native <select> HTML elements. For custom dropdowns (React/Material UI), use click() on the dropdown trigger then findElement() on the options.

Follow AutomateQA

Related Topics