Saturday, September 24, 2016

How to work with drop down button in Selenium webdriver

There are multiple methods to select an option from drop-down. We can select the value from the drop down by using below 3 methods.

1. selectByValue  - Select by value of option in drop down
2. selectByVisibleText - Select by the text displayed in drop down
3. selectByIndex  - Select by index of option in drop down

Refer to below screenshot for an example of HTML code of drop down in a website

So as per HTML code, if we need to select 'Male' from drop-down, we have 3 options to select it.
1. By value - 1 ( As it is defined in HTML code)
2. By Text - Male (It is case sensitive. so follow it)
3. By index - 1 (1st option in drop down always has index = 0)

Now comes the webdriver code:
1. Select gender= new Select(driver.findElement(By.xpath(enter xpath of drop-down here)));
2. gender.selectByValue("1"); // Selecting by value
2. gender.selectByVisibleText("Male"); // Selecting by visible text in drop-down
2. gender.selectByIndex(1); // Selecting by index

The above steps will select a value from drop down.
If you still face any issue, please write in comments section.