How To Select an Option From A DropDown List

In Selenium Webdriver, we have classes like “Select” which helps in interaction with the options of a drop down list. In this class, certain methods are defined using which we can select a particular option of a drop down list. I am going to explain it step by step.

1. In Eclipse, make a demo class and name it as “test1” . Here we will take makemytrip.com as an example. So in driver.get(url), you need to mention :

driver.get(“http://www.makemytrip.com/”) ;

2

 

2. In Select class we have mainly three methods :

selectByVisbileText()

selectByValue()

selectByIndex()

To get any option from the drop down list we can implement any of the above mentioned methods.

3. The first thing we need to do is, create an instance of Select class and then we can call any of the methods by providing the value we want to select.

3

 

The code you need to add is :

Select ss=new Select(driver.findElement(By.id(“class_selector”)));
ss.selectByVisibleText(“Business”);

This code will allow you select the Business from the available options under Class on the makemytrip site.

4. The other method we have is selectByValue(), here while locating the web element you can get the value which you need to pass to this method in order to select the particular option. For this the code you need to add is :

Select ss=new Select(driver.findElement(By.id(“class_selector”)));
ss.selectByValue(“B”);

4

 

5. The third method we are left with is selectByIndex(). In this method, you need to pass the index of the value from the drop down which you want to select. If you want to select the first value, you can pass the index as 1 and if you want to select the 4th value then you can pass the index as 4. For this the code you need to write is :

Select ss=new Select(driver.findElement(By.id(“class_selector”)));
ss.selectByIndex(2);

5

 

So these are the three methods of Select class which we can use to select the options from a drop down list…!!!

Add Comment