Handling Dropdowns in Selenium WebDriver: Automating Dropdown Selection

Master dropdown handling in Selenium WebDriver using Java. This tutorial provides code examples demonstrating how to locate dropdowns, select options using the Select class (selectByVisibleText, selectByIndex, selectByValue), and automate dropdown interactions in your Selenium tests.



Handling Dropdowns in Selenium WebDriver

Dropdowns (also known as selection lists) are common UI elements allowing users to choose from a list of options. Selenium WebDriver provides the Select class to automate interactions with dropdowns. This guide demonstrates how to select options from a dropdown using Selenium WebDriver (using Java).

The Selenium Select Class

The Select class provides methods for selecting and deselecting options in a dropdown. First, you need to locate the dropdown element using one of Selenium's locator strategies (e.g., By.id(), By.name(), etc.). Then, create a Select object, passing the located dropdown element as an argument to its constructor.

Creating a Select Object

WebElement dropdownElement = driver.findElement(By.id("myDropdown"));
Select select = new Select(dropdownElement);
            

Selecting Options from a Dropdown

The Select class offers three main methods for selecting options:

  1. selectByIndex(index): Selects an option by its index (starting from 0).
  2. selectByValue(value): Selects an option by its value attribute.
  3. selectByVisibleText(text): Selects an option by its visible text.

Example: Selecting a Dropdown Option

Let's automate selecting an option from a dropdown on a webpage (https://www.testandquiz.com/selenium/testing.html). The test will open the page and select the "Database Testing" option from a dropdown with the id "testingDropdown".

  1. Set up your Environment: Ensure you have Selenium WebDriver (and ChromeDriver) configured correctly.
  2. Launch Chrome: Use System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe"); and then `WebDriver driver = new ChromeDriver();`
  3. Navigate to URL: Use `driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");`
  4. Locate Dropdown: Find the dropdown using a suitable locator (e.g., By.id("testingDropdown")).
  5. Select Option: Use selectByVisibleText() to select the desired option:
  6. Selecting Dropdown Option
    
    Select dropdown = new Select(driver.findElement(By.id("testingDropdown")));
    dropdown.selectByVisibleText("Database Testing");
                    
  7. Close the browser: `driver.quit()`