Q8 of 37 · Selenium
How do you handle a dropdown in Selenium WebDriver?
Short answer
Short answer: For native `<select>`, wrap the element in `Select` and use `selectByVisibleText`, `selectByValue`, or `selectByIndex`. For custom dropdowns (divs, ARIA listbox, autocomplete), Select doesn't apply — click to open, then click the option.
Detail
Selenium has two completely different paths depending on whether the dropdown is a real <select> or a custom widget — and confusing them is the most common bug.
Native <select> — the HTML element. Wrap it in Selenium's Select helper:
Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("United Kingdom");
country.selectByValue("GB");
country.selectByIndex(2);
Select also exposes getOptions(), getFirstSelectedOption(), and (for multi-selects) deselectAll().
Custom dropdowns — anything built with <div> / <ul> / Material UI / React Select / autocomplete combobox. Select will throw UnexpectedTagNameException because the root isn't a <select>. The handling is browser-as-user:
- Click the trigger to open the dropdown.
- Wait for the option list to render (often a portal mounted to
<body>). - Click the desired option.
- (For autocomplete) Type the search text first, then click the suggestion.
driver.findElement(By.cssSelector("[data-test=country-dropdown]")).click();
new WebDriverWait(driver, Duration.ofSeconds(5))
.until(ExpectedConditions.elementToBeClickable(
By.xpath("//li[@role='option' and text()='United Kingdom']")
))
.click();
The interview signal: knowing Select only works on <select> and instinctively reaching for click-and-pick for everything else.