Selenium Dropdowns
The Select Class
Standard HTML dropdown menus use the select tag with option tags inside. Selenium provides a special Select class built specifically for this structure.
Diagram: A Dropdown Structure
<select id="country">
<option>India</option>
<option>USA</option>
<option>Canada</option>
</select>
Select Object
|
|-- selectByVisibleText("USA")
|-- selectByValue("us")
|-- selectByIndex(1)
Creating A Select Object
WebElement dropdownElement = driver.findElement(By.id("country"));
Select countryDropdown = new Select(dropdownElement);
Wrapping a WebElement inside the Select class unlocks dropdown-specific methods.
Selecting An Option
selectByVisibleText()
Chooses an option using the text a user sees on screen.
countryDropdown.selectByVisibleText("Canada");selectByValue()
Chooses an option using its value attribute, which may differ from the visible text.
countryDropdown.selectByValue("ca");selectByIndex()
Chooses an option using its position, starting from zero.
countryDropdown.selectByIndex(2);
Reading The Selected Option
WebElement selected = countryDropdown.getFirstSelectedOption(); System.out.println(selected.getText());
This prints the currently selected option, useful for confirming a dropdown holds the correct default value.
Multi-Select Dropdowns
Some dropdowns allow multiple selections at once, marked with the multiple attribute in HTML.
countryDropdown.selectByVisibleText("India");
countryDropdown.selectByVisibleText("USA");
List<WebElement> allSelected = countryDropdown.getAllSelectedOptions();
System.out.println("Total selected: " + allSelected.size());
This selects two countries and then counts how many options are currently active.
deselectAll()
Clears every selected option in a multi-select dropdown at once.
countryDropdown.deselectAll();
Handling Non-Standard Dropdowns
Many modern websites build custom dropdowns using div and li tags instead of the select tag. The Select class does not work on these. Instead, treat them as regular clickable elements.
driver.findElement(By.id("custom-dropdown")).click();
driver.findElement(By.xpath("//li[text()='Canada']")).click();
This clicks the dropdown to open it, then clicks the matching list item to make the choice, mimicking exactly what a real user does.
Practical Example
An online course form asks students to pick their experience level from a dropdown with options Beginner, Intermediate, and Advanced.
Select levelDropdown = new Select(driver.findElement(By.id("experience-level")));
levelDropdown.selectByVisibleText("Beginner");
This picks Beginner automatically, saving a tester from manually selecting the option during every test run.
