Selenium WebDriver-Dropdown Handling

How to Select Value from DropDown using Selenium Webdriver

In this tutorial, we will learn how to handle the drop-down in the Selenium WebDriver.

Selenium Web driver-Dropdown Handling
  • The drop-down always implemented using the SELECT Html tag.
  • The drop down is a unique element in the selenium web driver.
  • To handle the drop-down, we should take the help of the SELECT class.
  • The select class is used to select and deselect the options in a drop-down.
  • The Contains of the drop-down used the OPTIONS html tag.
  • The Option may or may not fixed, but it always depends on the drop-down, which is available in the UI.

The object of select class can be initialized by passing the drop-down element as a parameter to its constructor which is as shown below:

WebElement dwd=driver.findElement(By.id("month"));
Select sel=new Select(dwd); 
Selenium Web driver-Dropdown Handling 1

To select an option from the drop-down menu, following methods are provided by the web driver,

  • Operational method
  • Verification method
  • Data capture method

The Operational commands are used to select and deselect the index value, visible text, and value attribute of drop-down options.

Some of the most used operational methods are as follows:

Drop-down Methods Description Command Syntax
Operational Method
selectByVisibleText() This method is used to select options with the help of text. selectByVisibleText(String arg0):void sel. selectByVisibleText(“value of the visible text”);
selectByIndex() This method is used to select options by its index value which starts with “0.” selectByIndex(int index):void sel. selectByIndex(value of index);
selectByValue() This method is used to select options by its value attribute. selectByValue(Sting arg0):void sel.selectbyvalue(“value of value attribute”);
deselectByVisibleText() It is used to deselect all the options which displays the text matching value. deselectByVisibleText(String arg0):void sel.deselectByVisibleText(value of the visible text”);
deselectAll() It is used to deselect all the selected options. And it is applicable only when multiple drop-down option is selected. deselectAll():void sel.deselectAll();
deselectByIndex() It is used to deselect the options by its index value. deselectByIndex(int index):void sel.deselectByIndex();
deselelctByValue() This method is used to deselect all the options by its value attribute. Sometimes value attribute “value” is not the same. deselectByValue(String arg0):void sel.deselectByValue();
Verification Method
IsMultiple() This method return the Boolean value (true/false) if the drop down allows multiple selection or not. isMultiple():boolean sel.isMultiple()
Data Capture Method
getOptions() This method is used to capture all options related to the select tag. It will return List<WebElements> getOptions():List<webElement> List<WebElement>lst=sel.getOptions();
getAllSelectedOptions() This method is used to capture the all the selected options. getAllSelectedOptions():WebElement List<WebElement>lst=sel.getAllSelectedOptions();
getFirstSelectedOptions() This method is used to capture the first selected option in the case of multi -selection. getFirstSelectedOptions():WebElement   List<WebElement>lst=sel.getFirstSeelctedOptions();

Let us take a sample test script in which we will try to cover mostly used operational_controls Commands and verification command,

For our testing purpose, we are using the Facebook login page to perform all the actions in the drop-down element.

In this test case, we will automate the following test scenarios:

Steps Action Method Used Input Excepted Result
1. Open the Google Chrome Browser. System.setProperty()   The Chrome browser must be opened.
2. Navigate to the Facebook login page. get() https://www.facebook.com The Facebook login page must be displayed.
3. Identify the day dropdown element, and create a select class object. selectByVisibleText() Day=10 The day should be selected in the dropdown.
4. Identify the month dropdown element. selectByIndex() Month=mar The month should be selected in the dropdown.
5. Identify the year drop down element. selectByVIsibleText() Year=2015 The year should be selected in the dropdown.
6 Identify that the drop down is multi-selected or not. isMultiple()   Print the Boolean value (true /false).
7. Close the Browser close()   The browser should be closed.

Open the Eclipse IDE and the existing test suite new_test, which we have created in WebDriver Installation section of the WebDriver tutorial.

Then, right-click on the src folder and create a new Class File from New ? Class.

Selenium Web driver-Dropdown Handling 2
  • Give the Class name as Drop_down and click onthe Finish button.
Selenium Web driver-Dropdown Handling 3

We are creating our test case step by step to give you a complete understanding of Operational controls Commands in WebDriver.

Step1:

To launch the Google Chrome browser, we need to download the ChromeDriver.exe file and set the system property to the path of ChromeDriver.exe file.

Here is the code for setting the system property for the google chrome:

//set the system property of Google Chrome
System.setProperty("webdriver.chrome.driver","C:\\Users\\JTP\\Downloads\\chromedriver_win32\\chromedriver.exe");                                                                                           
// create driver object for CHROME browser
WebDriver driver=new ChromeDriver(); 

Step2:

Now, we will navigate to the desired URL:

//navigate to Facebook login page
driver.get("https://www.facebook.com"); 

Step3:

First, we will identify the day dropdown element in the Facebook login page and select Inspect element field.

Selenium Web driver-Dropdown Handling 4

The developer tool window will be launched, with all the specific codes used in the development of the day dropdown.

Selenium Web driver-Dropdown Handling 5
//identify the expected drop down element in UI    
WebElement dwd=driver.findElement(By.id("day"));
//create an object to "select" class and pass select drop down element as an argument.
Select sel=new Select(dwd);
//perform an action on the drop down using select class method
sel.selectByVisibleText("10");
Thread.sleep(3000); 

Step4:

Now, we are moving to next steps, where we will identify the month dropdown element in the Facebook login page and select the inspect element field

Selenium Web driver-Dropdown Handling 6

The developer tool window will be launched, with all the specific codes used in the development of the month dropdown.

Selenium Web driver-Dropdown Handling 7
//select the value from the month drop down
WebElement dwd1=driver.findElement(By.id("month"));
//create an object to "select" class and pass select drop down element as an argument.
Select sel1=new Select(dwd1);
//perform an action on the drop down using select class method
sel1.selectByIndex(3);
Thread.sleep(3000); 

Step5:

After that, we will identify the year dropdown element in the Facebook Login page and select the Inspect element field.

Selenium Web driver-Dropdown Handling 8

The developer tool window will be launched, with all the specific codes used in the development of the year dropdown.

Selenium Web driver-Dropdown Handling 9
//select the value from the year dropdown
WebElement dwd2=driver.findElement(By.id("year"));
//create an object to "select" class and pass select drop down element as an argument.
Select sel2=new Select(dwd2);                             
//perform an action on the drop down using select class method
sel2.selectByVisibleText("2015");
Thread.sleep(3000); 

Step6:

And now, we identify that the drop-down is multi-selected or not; if it is multi-selected, then it will print the Boolean value true; otherwise, it will print false.

//identify the Multi-select drop down in UI
System.out.println(sel.isMultiple()); 

Step7:                                                                                 

Finally, we terminate the process and close the browser.

 //Close the browser
 driver.close();   

After that, our final test script will look like this:

package testpackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class Drop_down {
public static void main(String[] args) throws InterruptedException  {
//set the system property
System.setProperty("webdriver.chrome.driver", C:\\Users\\JTP\\Downloads\\chromedriver_win32\\chromedriver.exe");         
//create driver class object
WebDriver driver = new ChromeDriver();
//maximize he window size
driver.manage().window().maximize();                 
//navigate to the RL
driver.get("https://www.facebook.com/");        
//identify the expected drop down element in UI
WebElement dwd=driver.findElement(By.id("day"));
//create an object to "select"class and pass select drop down element as an argument
Select sel=new Select(dwd);
//perform an action on the drop down using select class method
sel.selectByVisibleText("10");
Thread.sleep(3000);
//select the value from the month drop down
WebElement dwd1=driver.findElement(By.id("month"));
//create an object to "select" class and pass select drop down element as an argument
Select sel1=new Select(dwd1);  
//perform an action on the drop down using select class method
sel1.selectByIndex(3);
Thread.sleep(3000);       
//select the value from the year drop down
WebElement dwd2=driver.findElement(By.id("year"));
//create an object to "select" class and pass select drop down element as an argument
Select sel2=new Select(dwd2);  
//perform an action on the drop down using select class method
sel2.selectByVisibleText("2015");
Thread.sleep(3000);       
//identify the Multi-select drop down in UI
System.out.println(sel.isMultiple());
//close the browser
driver.close();                                    
}
} 
  • To run the test script in Eclipse, right-click on the window and then click Run as ? Java application.
  • The test script will be launched in the chrome browser and automate all the test scenarios.
Selenium Web driver-Dropdown Handling 10
  • The output of all the print command is as shown below:
Selenium Web driver-Dropdown Handling 11

Example2:

Let us take one more example, where we will work with multi-select dropdown or select all the values from the dynamic multi-selected dropdown and deselect the chosen value.

We are creating a one sample html code to give you a better understanding of verification and operational methods and how we use deselect methods in selenium WebDriver.

Steps Action Method Used Input Excepted Result
1. Open the Google Chrome Browser. System.setProperty()   The Chrome browser must be opened.
2. Creating one html file and navigate to the given URL. get() file:///D:/shivani/selenium%20web%20driver/example%20program/dd.html The Facebook login page must be displayed.
3. Identify the multi-select drop down in UI using a select class object.     The Multi-select drop-down should be selected.
4. Identify that the drop down is multi-selected or not. isMultiple()   Print the Boolean value (true /false).
5. Deselect the selected option. deselectByVisibleText() deselectByIndex() deselectall()       Selected options should be deselected.
6. Close the Browser close()   The browser should beclosed.

 Job Portal 

Select Skills

We will see all the steps one by one to give you a better understanding of the multi-select drop-down,

Follow the same step1 of the previous example.

Step2:

Now, we will navigate to the URL:

//navigate to given URL
driver.get("file:///D:/shivani/selenium%20web%20driver/example%20program/dd.html"); 

Step3:

To identify the multi-select drop-down, right-click on the dropdown and select the inspect element field.

Selenium Web driver-Dropdown Handling 12

The developer tool window will be launched, with all the specific codes which is shown below,

Selenium Web driver-Dropdown Handling 13

Here the sample code,

//identify the multi-select drop down in UI
Select sel =new Select(driver.findElement(By.xpath("//select[@multiple='multiple']")));
System.out.println("selected sucessfully"); 

Step4:

After that, in our next step, we will check whether the drop-down is multi-selected or not using verification i.e. ismultipe() method.

Here the sample code,

//check whether drop down is Multi-select or not?
boolean status=sel.isMultiple();
if(status)
{
//select multiple value from drop down
for(int i=0;i<5;i++)
{
sel.selectByIndex(i);
}
}
else{
System.out.print("it is not a multi-select dropdown");
} 

Step5:

And, we will deselect the selected options by using operational i.e., deselectByVisibleText(),deselectByIndex(), and deselectall() methods.

Here the sample code,

//deselect the selected option using deselectByVisibleText() method
sel.deselectByVisibleText("C language");
Thread.sleep(3000);
//deselect the selected option using deselectByIndex() method
sel.deselectByIndex(2);
Thread.sleep(3000);
//deselect all the selected option using deselectall() method
sel.deselectAll();
Thread.sleep(3000);
System.out.println("deselection successfully"); 

Step6:

After, deselecting the options by using operational methods, we will close the browser.

//close the browser
driver.close(); 

After completing all the steps successfully, our final test script will look like this:

package testpackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class Drop_down2 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\JTP\\Downloads\\chromedriver_win32\\chromedriver.exe");
//create driver class object
WebDriver driver = new ChromeDriver();
//maximize he window size
driver.manage().window().maximize(); 
driver.get("file:///D:/shivani/selenium%20web%20driver/example%20program/dd.html");
//identify the multi-select drop down in UI
Select sel =new Select(driver.findElement(By.xpath("//select[@multiple='multiple']")));
System.out.println("selected sucessfully");
//check whether drop down is Multi-select or not?
boolean status=sel.isMultiple();
if(status)
{
//select multiple value from drop down
for(int i=0;i<5;i++)
{
sel.selectByIndex(i);
}
}
else{
System.out.print("it is not a multi-select dropdown");
}
//deselect the selected option using deselectByVisibleText() method
sel.deselectByVisibleText("C language");
Thread.sleep(3000);
//deselect the selected option using deselectByIndex() method
sel.deselectByIndex(2);
Thread.sleep(3000);
//deselect all the selected option using deselectall() method
sel.deselectAll();
Thread.sleep(3000);
System.out.println("deselection succesfully");
//close the browser
driver.close();
}
} 

After running this test script successfully, it launched the chrome browser and automated all the test scenarios, which is as shown below:

Selenium Web driver-Dropdown Handling 14

Example3:

In this example, we will understand the data capture methods and capture all the options /values from the dynamic dropdown and display in the console.

We will also find the expected value from the dropdown and select the expected value if it is available.

We will take help from the above html code and follow the same process,

Steps Action Method Used Input Excepted Result
1. Open the Google Chrome Browser. System.setProperty()   The Chrome browser must be opened.
2. Creating one html file and navigate through the given URL. get() file:///D:/shivani/selenium%20web%20driver/example%20program/dd.html Given URL page must be displayed.
3. Identify the multi-select drop down in UI using a select class object     The Multi-select drop-down should be selected.
4. Capture the data with the help of data capture methods and also getting the option count. getOptions(), getAllSelectedOptions()   The data should be captured, and the count of the options should be printed.
5. Display the content from the drop-down.       The content should be displayed.
6. Close the Browser close()   The browser should beclosed.

We will see all the steps one by one to give you a better understanding of the data-capture methods,

Follow the same step1 of Example1.

Step2:

Now, we will navigate to the URL:

//navigate to the URL
driver.get("file:///D:/shivani/selenium%20web%20driver/example%20program/dd.html");
String expval="Selenium";
boolean flag=false; 

Step3:

To identify the multi-select drop-down, right-click on the dropdown and select the inspect element field.

Selenium Web driver-Dropdown Handling 15

The developer tool window will be launched, with all the specific codes which is shown below,

Selenium Web driver-Dropdown Handling 16

Here the sample code,

//identify the multi-select drop down in UI
Select sel =new Select(driver.findElement(By.xpath("//select[@multiple='multiple']")));
System.out.println("selected sucessfully"); 

Step4:

Once we identify that it is multi-select drop-down, we will capture all the data with the help of data capture methods and getting the option count.

Here the sample code,

//capture all data 
Listlst=sel.getOptions();
Listlst1=sel.getAllSelectedOptions();
//get the option count
System.out.println(lst.size()); 

Step5:

And, in the next step, we will display the content from the drop-down,

Here the sample code,

//displayl the content from the dynamic dropdown
for(int i=0;i



Step6:

After that, we will close the browser.

//close the browser
driver.close();
After completing all the steps successfully, our final test script will look like this:
package testpackage;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class Drop_down3 {
public static void main(String[] args) throws InterruptedException {
//set the system property
System.setProperty("webdriver.chrome.driver", C:\\Users\\JTP\\Downloads\\chromedriver_win32\\chromedriver.exe");
//create driver class object
WebDriver driver = new ChromeDriver();
//maximize he window size
driver.manage().window().maximize(); 
driver.get("file:///D:/shivani/selenium%20web%20driver/example%20program/dd.html");
String expval="Selenium";
boolean flag=false;
//identify the multi-select drop down in UI
Select sel =new Select(driver.findElement(By.xpath("//select[@multiple='multiple']")));
System.out.println("selected successfully");
//capture all data 
Listlst=sel.getOptions();
Listlst1=sel.getAllSelectedOptions();
//get the option count
System.out.println(lst.size());
//display all the content from the dynamic dropdown
for(int i=0;i<lst.size();i++)
{
String actval=lst.get(i).getText();
if(actval.equals(expval))
{
flag=true;
}
sel.selectByVisibleText(expval);
System.out.println("expceted value is available=pass");
Thread.sleep(3000);
break;
}
//close the driver
driver.close();
}
} 

After running the test script successfully, it launched the chrome browser and automated all the test scenarios, which are as shown below:

Selenium Web driver-Dropdown Handling 17

And the output of all the print command is as shown below,

Selenium Web driver-Dropdown Handling 18