In order to select a dropdown value with Selenium WebDriver you have to create a Select (in C# it’s called SelectElement) element and not use the default WebElements.
WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
or pass it directly to the Select element:
Select dropdown = new Select(driver.findElement(By.id("mySelect")));
2. To select an option you can do:
All select/deselect methods will throw NoSuchElementException if no matching option elements are found. Select by Visible Text (select all options that display text matching the argument):
dropdown.selectByVisibleText("Italy");
or
Select by Index (select the option at the given index. This is done by examining the “index” attribute of an element, and not merely by counting):
dropdown.selectByIndex(2);
or
Select by Option Value (select all options that have a value matching the argument)
dropdown.selectByValue("option2");
3. To deselect an option you can do:
Also, the deselect method will throw UnsupportedOperationException ff the SELECT does not support multiple selections
Deselect all selected entries, valid only when the SELECT supports multiple selections:
5. In order to get the list of options from a dropdown element:
WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
List options = dropdown.getOptions();
for (WebElement option : options) {
System.out.println(option.getText()); //output "option1", "option2", "option3"
}
You can also use LoadFocus.com to automate your UI Website tests and run the easily from the cloud every 30 minutes and get notified when they fail. Try it now.