Careeroza
Dropdowns with Select
An HTML select
<select id="sort">
<option value="relevance" selected>Relevance</option>
<option value="price-asc">Price: Low to High</option>
<option value="price-desc">Price: High to Low</option>
<option value="newest">Newest First</option>
</select>The Select Class
import org.openqa.selenium.support.ui.Select;
Select sort = new Select(driver.findElement(By.id("sort")));
sort.selectByVisibleText("Price: Low to High"); // what the user sees
sort.selectByValue("newest"); // value attribute
sort.selectByIndex(2); // 0-based position
System.out.println("Selected: " + sort.getFirstSelectedOption().getText());
for (WebElement option : sort.getOptions()) System.out.println(" - " + option.getText());
System.out.println("Multiple? " + sort.isMultiple());Example
Output:
Run SortDropdownTest.main()Example output
Selected: Price: High to Low - Relevance - Price: Low to High - Price: High to Low - Newest First Multiple? false
Custom Dropdowns
Many modern sites build dropdowns from <div> and <li>, not <select>. Select then throws UnexpectedTagNameException: Element should have been "select" but was "div". Click to open, then click the option:
driver.findElement(By.cssSelector(".city-picker")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//li[normalize-space()='Bengaluru']"))).click();