Friday, July 29, 2016

How to Select a Dropdown

You all are wondering  how to select/deselect a drop-down value with Selenium WebDriver 

First of all we need to import Select class
1
import org.openqa.selenium.support.ui.Select;
Here the glimpse how we are going to use Select class
1
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Let’s consider the following drop-down example:
<select id="mySelect">
<option value="option1">Apple</option>
<option value="option2">Mango</option>
<option value="option3">Orange</option>
</select>

1. Identify the select HTML element:

1
2
WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
or pass it directly to the Select element:
1
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):
1
dropdown.selectByVisibleText("Apple");
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):
1
dropdown.selectByIndex(2);
or
Select by Option Value (select all options that have a value matching the argument)
1
dropdown.selectByValue("option2");

3. To deselect an option you can do:

Also, the deselect method will throw UnsupportedOperationException if the SELECT does not support multiple selections
Deselect all selected entries, valid only when the SELECT supports multiple selections:
1
dropdown.deselectAll();
Deselect by Visible Text:
1
dropdown.deselectByVisibleText("Apple");
Deselect by Index
1
dropdown.deselectByIndex(2);
Deselect by value:
1
dropdown.deselectByValue("option2");

4. In order to get the selected option:

1
2
3
4
5
6
WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
dropdown.selectByVisibleText("Apple");
WebElement option = dropdown.getFirstSelectedOption();
System.out.println(option.getText()); //output "Apple"

5. In order to get the list of options from a drop-down element:

1
2
3
4
5
6
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"
}