Handle the List Box (Drop Down List and Multi-Select List) using Select class of Selenium WebDriver

02 April, 2014
There is no method in WebElement class to select the option present in List Box. In order to handle the List box we use the methods available under Select Class of Selenium WebDriver.

In order to handle the List Box we should perform the following three steps:

1. Find the DropDown List element.
2. Create instance of Select class by specifying the above dropdown list element as argument for Select class constructor.
3. Call anyone of the selectBy method of the Select class.

We have the following selectBy methods for different actions:

1. selectByIndex(int index);
2. selectByValue(String value);
3. selectByVisibleText(String text);
4. deselectByIndex(int index);
5. deselectByValue(String value);
6. deselectByVisibleText(String text);
7. deselectAll();

When we use any of the selectBy methods on multiselect List box it will keep the already selected options as it is and it will select the newly specified option.

Example code:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Dropdown_SelectClass{

 public static void main(String[] args) throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  //Find the dropdown list element
  WebElement cSelect = driver.findElement(By.id("countrySelect"));
  //Create the instance of the Select class
  Select select = new Select(cSelect);
  //Call the required method

No comments:

Post a Comment