Chapter 4: Dropdown select, xpath and cssSelector with Example

The ‘Select’ class in Selenium WebDriver is used for selecting and deselecting options in a dropdown. Selenium has Select class. (;).We can select value from   given dropdown menu.

The big advantage to working with drop down is that you don’t want to work with them as WebElements, but instead create a Select element for them. The Select class (java) includes utility methods that allows you to perform common tasks. We have to import a package of ‘Select’ class in selenium.

We can used this select class with the help of below steps.

Firstly, Identify WebElement with Select tag, that is for your dropdown.

Ex - WebElement element = driver.findElement(" "));

Then, create an object of Select class.

Ex. Select s1 = new Select(listbox);

Then Select the value by one of the applicable methods like ByVisibleText, ByIndex ,ByValue….whichever can be applied.

How to select an option from drop-down menu?

WebDriver provides three ways to select an option from the drop-down menu.

1. selectByIndex – It is used to select an option based on its index, beginning with 0.

Ex: dropdown.selectByIndex(int);  

2. selectByValue – It is used to select an option based on its ‘value’ attribute.

Ex: dropdown.selectByValue("Text");  

3. selectByVisibleText – It is used to select an option based on the text over the option.

 Ex: dropdown.selectByValue("Text");  

 As an example, we use Mercury Tours’ login page( ) and select the Flight details from the “Departing From” drop-down box .  

  Step 1

Import the “Select” package.

Step 2

Declare the drop-down element as an instance of the Select class. In the example below, we named this instance as “seleCountry”.

Step 3

We can now start controlling “seleCountry” by using any of the available Select methods. The sample code below will select the option “SWEDEN.”

Complete Code:

package testology;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class Login
  public static void main(String[] args) 
System.setProperty("webdriver.driver.chromedriver", "chromedriver.exe");
		WebDriver driver = new ChromeDriver();
WebElement name = driver.findElement("userName"));
// get the webelement corresponding to password (passwordfield)
WebElement password = driver.findElement("password"));
// to click on submit button
WebElement submitbutton = driver.findElement(By.cssSelector
Select departingflight = new Select(driver.findElement
// close the chrome browser

See above video to understand this in detail. The practice.html file used in above video can be downloaded from here.