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
Selectclass only works with native<select>HTML elements. For custom dropdowns (React/Material UI), useclick()on the dropdown trigger thenfindElement()on the options.
