Dropdowns and Select Elements
Learn to interact with HTML select elements, custom dropdowns, and autocomplete inputs.
Selenium 3 & 4 Stable
Dropdown menus come in different forms: native HTML select elements, custom JavaScript-powered dropdowns, and autocomplete inputs. Each requires different handling techniques.
Native Select Elements
Selenium provides a Select class specifically for handling HTML <select> elements.
Using the Select Class
Selenium 3 & 4 Stable
import org.openqa.selenium.support.ui.Select;import org.openqa.selenium.WebElement;import org.openqa.selenium.By;
// Find the select elementWebElement selectElement = driver.findElement(By.id("country"));Select dropdown = new Select(selectElement);
// Select by visible text (what user sees)dropdown.selectByVisibleText("United States");
// Select by value attributedropdown.selectByValue("us");
// Select by index (0-based)dropdown.selectByIndex(2);
// Get currently selected optionWebElement selected = dropdown.getFirstSelectedOption();String selectedText = selected.getText();System.out.println("Selected: " + selectedText);
// Get all available optionsList<WebElement> allOptions = dropdown.getOptions();for (WebElement option : allOptions) { System.out.println(option.getText());}from selenium.webdriver.support.ui import Selectfrom selenium.webdriver.common.by import By
# Find the select elementselect_element = driver.find_element(By.ID, "country")dropdown = Select(select_element)
# Select by visible text (what user sees)dropdown.select_by_visible_text("United States")
# Select by value attributedropdown.select_by_value("us")
# Select by index (0-based)dropdown.select_by_index(2)
# Get currently selected optionselected = dropdown.first_selected_optionselected_text = selected.textprint(f"Selected: {selected_text}")
# Get all available optionsall_options = dropdown.optionsfor option in all_options: print(option.text)// Note: JavaScript Selenium doesn't have a built-in Select class// You need to work with the element directly or use helpers
const selectElement = await driver.findElement(By.id('country'));
// Select by visible text - click option with matching textconst options = await selectElement.findElements(By.tagName('option'));for (const option of options) { if (await option.getText() === 'United States') { await option.click(); break; }}
// Select by valueawait selectElement.findElement(By.css("option[value='us']")).click();
// Select by indexconst allOptions = await selectElement.findElements(By.tagName('option'));await allOptions[2].click();
// Get selected optionconst selectedOption = await selectElement.findElement(By.css('option:checked'));const selectedText = await selectedOption.getText();console.log(`Selected: ${selectedText}`);using OpenQA.Selenium.Support.UI;
// Find the select elementIWebElement selectElement = driver.FindElement(By.Id("country"));SelectElement dropdown = new SelectElement(selectElement);
// Select by visible text (what user sees)dropdown.SelectByText("United States");
// Select by value attributedropdown.SelectByValue("us");
// Select by index (0-based)dropdown.SelectByIndex(2);
// Get currently selected optionIWebElement selected = dropdown.SelectedOption;string selectedText = selected.Text;Console.WriteLine($"Selected: {selectedText}");
// Get all available optionsIList<IWebElement> allOptions = dropdown.Options;foreach (IWebElement option in allOptions){ Console.WriteLine(option.Text);}Multi-Select Dropdowns
Some select elements allow multiple selections:
Multi-Select Handling
Selenium 3 & 4 Stable
Select multiSelect = new Select(driver.findElement(By.id("skills")));
// Check if multi-select is enabledboolean isMultiple = multiSelect.isMultiple();
if (isMultiple) { // Select multiple options multiSelect.selectByVisibleText("Java"); multiSelect.selectByVisibleText("Python"); multiSelect.selectByValue("javascript");
// Get all selected options List<WebElement> selectedOptions = multiSelect.getAllSelectedOptions(); System.out.println("Selected " + selectedOptions.size() + " items");
// Deselect specific option multiSelect.deselectByVisibleText("Python");
// Deselect by value multiSelect.deselectByValue("javascript");
// Deselect all multiSelect.deselectAll();}multi_select = Select(driver.find_element(By.ID, "skills"))
# Check if multi-select is enabledis_multiple = multi_select.is_multiple
if is_multiple: # Select multiple options multi_select.select_by_visible_text("Java") multi_select.select_by_visible_text("Python") multi_select.select_by_value("javascript")
# Get all selected options selected_options = multi_select.all_selected_options print(f"Selected {len(selected_options)} items")
# Deselect specific option multi_select.deselect_by_visible_text("Python")
# Deselect by value multi_select.deselect_by_value("javascript")
# Deselect all multi_select.deselect_all()const multiSelectElement = await driver.findElement(By.id('skills'));const isMultiple = await multiSelectElement.getAttribute('multiple') !== null;
if (isMultiple) { // Select multiple options (Ctrl+Click simulation not needed for select) const options = await multiSelectElement.findElements(By.tagName('option'));
for (const option of options) { const text = await option.getText(); if (['Java', 'Python', 'JavaScript'].includes(text)) { await option.click(); } }
// Get all selected options const selectedOptions = await multiSelectElement.findElements( By.css('option:checked') ); console.log(`Selected ${selectedOptions.length} items`);
// Deselect by clicking again for (const option of options) { const text = await option.getText(); if (text === 'Python' && await option.isSelected()) { await option.click(); } }}SelectElement multiSelect = new SelectElement(driver.FindElement(By.Id("skills")));
// Check if multi-select is enabledbool isMultiple = multiSelect.IsMultiple;
if (isMultiple){ // Select multiple options multiSelect.SelectByText("Java"); multiSelect.SelectByText("Python"); multiSelect.SelectByValue("javascript");
// Get all selected options IList<IWebElement> selectedOptions = multiSelect.AllSelectedOptions; Console.WriteLine($"Selected {selectedOptions.Count} items");
// Deselect specific option multiSelect.DeselectByText("Python");
// Deselect by value multiSelect.DeselectByValue("javascript");
// Deselect all multiSelect.DeselectAll();}Custom Dropdowns
Many modern websites use custom dropdowns built with divs and JavaScript. These require different handling:
Custom Dropdown Interaction
Selenium 3 & 4 Medium
// Step 1: Click the dropdown trigger to open itWebElement dropdownTrigger = driver.findElement(By.className("dropdown-toggle"));dropdownTrigger.click();
// Step 2: Wait for options to be visibleWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));wait.until(ExpectedConditions.visibilityOfElementLocated( By.className("dropdown-menu")));
// Step 3: Click the desired optionWebElement option = driver.findElement( By.xpath("//div[@class='dropdown-menu']//span[text()='Option 2']"));option.click();
// Alternative: Use Actions for hover-activated dropdownsActions actions = new Actions(driver);WebElement menu = driver.findElement(By.className("menu-item"));actions.moveToElement(menu).perform();
// Wait and click submenu itemWebElement submenuItem = wait.until(ExpectedConditions.elementToBeClickable( By.className("submenu-item")));submenuItem.click();from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.action_chains import ActionChains
# Step 1: Click the dropdown trigger to open itdropdown_trigger = driver.find_element(By.CLASS_NAME, "dropdown-toggle")dropdown_trigger.click()
# Step 2: Wait for options to be visiblewait = WebDriverWait(driver, 10)wait.until(EC.visibility_of_element_located( (By.CLASS_NAME, "dropdown-menu")))
# Step 3: Click the desired optionoption = driver.find_element( By.XPATH, "//div[@class='dropdown-menu']//span[text()='Option 2']")option.click()
# Alternative: Use Actions for hover-activated dropdownsactions = ActionChains(driver)menu = driver.find_element(By.CLASS_NAME, "menu-item")actions.move_to_element(menu).perform()
# Wait and click submenu itemsubmenu_item = wait.until(EC.element_to_be_clickable( (By.CLASS_NAME, "submenu-item")))submenu_item.click()const { until, Actions } = require('selenium-webdriver');
// Step 1: Click the dropdown trigger to open itconst dropdownTrigger = await driver.findElement(By.className('dropdown-toggle'));await dropdownTrigger.click();
// Step 2: Wait for options to be visibleawait driver.wait( until.elementLocated(By.className('dropdown-menu')), 10000);
// Step 3: Click the desired optionconst option = await driver.findElement( By.xpath("//div[@class='dropdown-menu']//span[text()='Option 2']"));await option.click();
// Alternative: Use Actions for hover-activated dropdownsconst actions = driver.actions({ async: true });const menu = await driver.findElement(By.className('menu-item'));await actions.move({ origin: menu }).perform();
// Wait and click submenu itemconst submenuItem = await driver.wait( until.elementIsVisible(driver.findElement(By.className('submenu-item'))), 10000);await submenuItem.click();using OpenQA.Selenium.Support.UI;using OpenQA.Selenium.Interactions;
// Step 1: Click the dropdown trigger to open itIWebElement dropdownTrigger = driver.FindElement(By.ClassName("dropdown-toggle"));dropdownTrigger.Click();
// Step 2: Wait for options to be visibleWebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));wait.Until(ExpectedConditions.ElementIsVisible( By.ClassName("dropdown-menu")));
// Step 3: Click the desired optionIWebElement option = driver.FindElement( By.XPath("//div[@class='dropdown-menu']//span[text()='Option 2']"));option.Click();
// Alternative: Use Actions for hover-activated dropdownsActions actions = new Actions(driver);IWebElement menu = driver.FindElement(By.ClassName("menu-item"));actions.MoveToElement(menu).Perform();
// Wait and click submenu itemIWebElement submenuItem = wait.Until(ExpectedConditions.ElementToBeClickable( By.ClassName("submenu-item")));submenuItem.Click();Autocomplete/Typeahead Inputs
Autocomplete fields require typing to trigger suggestions:
Autocomplete Field Handling
Selenium 3 & 4 Medium
// Find the autocomplete inputWebElement searchInput = driver.findElement(By.id("city-search"));
// Clear and type to trigger suggestionssearchInput.clear();searchInput.sendKeys("New Yo");
// Wait for suggestions to appearWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));wait.until(ExpectedConditions.visibilityOfElementLocated( By.className("autocomplete-suggestions")));
// Option 1: Click a specific suggestionWebElement suggestion = driver.findElement( By.xpath("//div[@class='autocomplete-item'][contains(text(), 'New York')]"));suggestion.click();
// Option 2: Use keyboard to selectsearchInput.sendKeys(Keys.ARROW_DOWN); // Move to first suggestionsearchInput.sendKeys(Keys.ARROW_DOWN); // Move to second suggestionsearchInput.sendKeys(Keys.ENTER); // Select current suggestion
// Verify selectionString selectedValue = searchInput.getAttribute("value");System.out.println("Selected: " + selectedValue);# Find the autocomplete inputsearch_input = driver.find_element(By.ID, "city-search")
# Clear and type to trigger suggestionssearch_input.clear()search_input.send_keys("New Yo")
# Wait for suggestions to appearwait = WebDriverWait(driver, 10)wait.until(EC.visibility_of_element_located( (By.CLASS_NAME, "autocomplete-suggestions")))
# Option 1: Click a specific suggestionsuggestion = driver.find_element( By.XPATH, "//div[@class='autocomplete-item'][contains(text(), 'New York')]")suggestion.click()
# Option 2: Use keyboard to selectsearch_input.send_keys(Keys.ARROW_DOWN) # Move to first suggestionsearch_input.send_keys(Keys.ARROW_DOWN) # Move to second suggestionsearch_input.send_keys(Keys.ENTER) # Select current suggestion
# Verify selectionselected_value = search_input.get_attribute("value")print(f"Selected: {selected_value}")// Find the autocomplete inputconst searchInput = await driver.findElement(By.id('city-search'));
// Clear and type to trigger suggestionsawait searchInput.clear();await searchInput.sendKeys('New Yo');
// Wait for suggestions to appearawait driver.wait( until.elementLocated(By.className('autocomplete-suggestions')), 10000);
// Option 1: Click a specific suggestionconst suggestion = await driver.findElement( By.xpath("//div[@class='autocomplete-item'][contains(text(), 'New York')]"));await suggestion.click();
// Option 2: Use keyboard to selectawait searchInput.sendKeys(Key.ARROW_DOWN); // Move to first suggestionawait searchInput.sendKeys(Key.ARROW_DOWN); // Move to second suggestionawait searchInput.sendKeys(Key.ENTER); // Select current suggestion
// Verify selectionconst selectedValue = await searchInput.getAttribute('value');console.log(`Selected: ${selectedValue}`);// Find the autocomplete inputIWebElement searchInput = driver.FindElement(By.Id("city-search"));
// Clear and type to trigger suggestionssearchInput.Clear();searchInput.SendKeys("New Yo");
// Wait for suggestions to appearWebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));wait.Until(ExpectedConditions.ElementIsVisible( By.ClassName("autocomplete-suggestions")));
// Option 1: Click a specific suggestionIWebElement suggestion = driver.FindElement( By.XPath("//div[@class='autocomplete-item'][contains(text(), 'New York')]"));suggestion.Click();
// Option 2: Use keyboard to selectsearchInput.SendKeys(Keys.ArrowDown); // Move to first suggestionsearchInput.SendKeys(Keys.ArrowDown); // Move to second suggestionsearchInput.SendKeys(Keys.Enter); // Select current suggestion
// Verify selectionstring selectedValue = searchInput.GetAttribute("value");Console.WriteLine($"Selected: {selectedValue}");Datepickers
Date pickers are often custom widgets requiring special handling:
Date Picker Handling
Selenium 3 & 4 Medium
// Method 1: Direct input (if allowed)WebElement dateInput = driver.findElement(By.id("date-field"));dateInput.clear();dateInput.sendKeys("12/25/2024");
// Method 2: Use JavaScript to set value (bypasses validation)JavascriptExecutor js = (JavascriptExecutor) driver;js.executeScript( "arguments[0].value = '2024-12-25'", dateInput);
// Method 3: Interact with calendar widgetWebElement dateField = driver.findElement(By.id("date-picker"));dateField.click(); // Opens calendar
// Navigate to correct month/yearWebElement nextMonth = driver.findElement(By.className("next-month"));nextMonth.click();
// Select the dayWebElement day = driver.findElement( By.xpath("//td[@data-date='25' and not(contains(@class, 'disabled'))]"));day.click();# Method 1: Direct input (if allowed)date_input = driver.find_element(By.ID, "date-field")date_input.clear()date_input.send_keys("12/25/2024")
# Method 2: Use JavaScript to set value (bypasses validation)driver.execute_script( "arguments[0].value = '2024-12-25'", date_input)
# Method 3: Interact with calendar widgetdate_field = driver.find_element(By.ID, "date-picker")date_field.click() # Opens calendar
# Navigate to correct month/yearnext_month = driver.find_element(By.CLASS_NAME, "next-month")next_month.click()
# Select the dayday = driver.find_element( By.XPATH, "//td[@data-date='25' and not(contains(@class, 'disabled'))]")day.click()// Method 1: Direct input (if allowed)const dateInput = await driver.findElement(By.id('date-field'));await dateInput.clear();await dateInput.sendKeys('12/25/2024');
// Method 2: Use JavaScript to set value (bypasses validation)await driver.executeScript( "arguments[0].value = '2024-12-25'", dateInput);
// Method 3: Interact with calendar widgetconst dateField = await driver.findElement(By.id('date-picker'));await dateField.click(); // Opens calendar
// Navigate to correct month/yearconst nextMonth = await driver.findElement(By.className('next-month'));await nextMonth.click();
// Select the dayconst day = await driver.findElement( By.xpath("//td[@data-date='25' and not(contains(@class, 'disabled'))]"));await day.click();// Method 1: Direct input (if allowed)IWebElement dateInput = driver.FindElement(By.Id("date-field"));dateInput.Clear();dateInput.SendKeys("12/25/2024");
// Method 2: Use JavaScript to set value (bypasses validation)IJavaScriptExecutor js = (IJavaScriptExecutor)driver;js.ExecuteScript( "arguments[0].value = '2024-12-25'", dateInput);
// Method 3: Interact with calendar widgetIWebElement dateField = driver.FindElement(By.Id("date-picker"));dateField.Click(); // Opens calendar
// Navigate to correct month/yearIWebElement nextMonth = driver.FindElement(By.ClassName("next-month"));nextMonth.Click();
// Select the dayIWebElement day = driver.FindElement( By.XPath("//td[@data-date='25' and not(contains(@class, 'disabled'))]"));day.Click();Common Dropdown Patterns
| Type | Recognition | Approach |
|---|---|---|
Native <select> | Has <option> children | Use Select class |
| Button dropdown | Div/button opens menu | Click trigger, then option |
| Autocomplete | Input shows suggestions | Type, wait, select |
| Hover menu | Opens on mouse hover | Use Actions.moveToElement |
Best Practices
- Identify dropdown type before writing code
- Use explicit waits for options to appear
- Verify selection after making it
- Handle timing - dropdowns often have animations
- Consider keyboard navigation as fallback
Next Steps
- Drag and Drop - Complex mouse interactions
- Keyboard Actions - Navigate with keyboard
- Explicit Waits - Wait for dropdown states