Selenium has Select
class designed to interact with drop down lists. Using it, we can easily choose
option by displayed text, index or value.
Example:
Consider a dropdown list as shown below:
Now we just need to pass WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("months")));
To select option say 'February', we can use any one of the method:
Select dropdown = new Select(driver.findElement(By.id("months")));
To select option say 'February', we can use any one of the method:
- dropdown.selectByVisibleText("February");
- dropdown.selectByValue("Feb");
- dropdown.selectByIndex(2);
I have created a generic class Dropdown with all 3 methods shown above, we just need to call it.
- Dropdown.selectByVisibleText(driver, By.id("months"), "February");
- Dropdown.selectByValue(driver, By.id("months"), "Feb");
- Dropdown.selectByIndex(driver, By.id("months"), 2);