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.

More details are available in theĀ Video Course on How to Select a Dropdown in Selenium WebDriver.

 

 

import org.openqa.selenium.support.ui.Select;

Use our previous post to locate elements with Selenium WebDriver.

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Let’s consider the following dropdown element for our example:

<select id="mySelect">
<option value="option1">France</option>
<option value="option2">Italy</option>
<option value="option3">Spain</option>
</select>

1. Identify the select HTML element:

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);

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.

 

Check also The Ultimate Selenium WebDriver Testing & Hands-on Guide – Online Course.