'Select'
class of Webdriver provides useful methods for interacting with select options.
We can perform operations on a select dropdown using the as below:
HTML Code:
<div>
<select
id="SelectID">
<option
value="colorred">Red</option>
<option
value="colorgreen">Green</option>
<option
value="colorblue">Blue</option>
</select>
</div>
Methods:
Selecting By Value:
Setting the value in the dropdown
using selectByValue() method:
Select select = new Select(driver.findElement(By.id("SelectID")));
Select select = new Select(driver.findElement(By.id("SelectID")));
select.selectByValue(“colorgreen”);
Selecting By Visible Text:
Setting the value in the dropdown
using selectByVisibleText() method
Select select = new Select(driver.findElement(By.id("SelectID")));
Select select = new Select(driver.findElement(By.id("SelectID")));
select.selectByVisibleText(“Green”);
Selecting By Index
Setting the value in the dropdown
using selectByIndex() method
Select select = new Select(driver.findElement(By.id("SelectID")));
Select select = new Select(driver.findElement(By.id("SelectID")));
select.selectByIndex(“2”);
MultiSelect:
In the above example step, we can
select multiple options, if it is allowed, just we need to fire the same
command repeatedly for multiple web elements:
Select dropdown = new
Select(driver.findElement(By.id("SelectID")));
dropdown.selectByVisibleText(“Red”);
dropdown.selectByVisibleText(“Green”);
dropdown.selectByVisibleText(“Blue”);
Iterating over web elements
We can also take it in the form of
list of web elements and iterate over it:
Select dropdown = new
Select(driver.findElement(By.id("SelectID")));
List <WebElement> Colors =
dropdown.getOptions();
int csize = Colors.size();
for(int i =0; i<csize ;
i++){
String svalue =
Colors.get(i).getText();
System.out.println(sValue);
}