How to select value from drop-down list in selenium webdriver

Select Class in Selenium

The Select Class in Selenium is a method used to implement the HTML SELECT tag. The html select tag provides helper methods to select and deselect the elements. The Select class is an ordinary class so New keyword is used to create its object and it specifies the web element location.

What is Select Class in Selenium?

In HTML, the dropdowns are generally implemented either using the <select> tag or the <input> tag. To perform certain operations on the dropdowns, which are declared using the <select> HTML tag, Selenium WebDrivers provides a class called "Select " class. As soon as you start typing the "Select " in your IDE, it will show the details as shown below:

How to select value from drop-down list in selenium webdriver

As we can see from the above screenshot, the "Select " class is provided by the "org.openqa.selenium.support.ui " package of Selenium WebDriver. You can create an object of the Select class, by-passing the object of the "WebElement" class, which shows the object returned by the corresponding locator of the WebElement.

So, you can create the object of the Select class by using the following syntax:

Select select = new Select(WebElement webelement);

The Select class constructor accepts one parameter: the WebElement object returned by the locators of the specified element.

The "Select " class provides various methods for handling the dropdown operations. The following figures list a few of them:

How to select value from drop-down list in selenium webdriver

Let's now understand the syntax and usage of various select and deselect methods provided by the "Select " class in Selenium WebDriver.

How to select a value from a dropdown in Selenium?

As highlighted in the above figure, the Select class of Selenium WebDriver provides the following methods to select an option/value from a drop-down (as highlighted by marker 1 in the above image):

  • selectByIndex
  • selectByValue
  • selectByVisibleText

Let's understand the syntax and usage of all these methods:

selectByIndex:

This method selects the dropdown option by its index number. We provide an integer value as the index number as an argument. It possesses the following syntax:

selectByIndex(int arg0) : void

i.e., it accepts the index of the dropdown value, which needs to be selected. The index starts at 0.

Suppose on the web page "https://demoqa.com/select-menu" we have the select the 4th value of the dropdown as highlighted below:

How to select value from drop-down list in selenium webdriver

As we can see, the above dropdown is being implemented using the <select> HTML tag, so we can use the "Select " class of Selenium WebDriver to select the option "Yellow " using the index as shown below:

// Create object of the Select class Select se = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']"))); // Select the option by index se.selectByIndex(3);

As we mentioned, the indices of dropdown start at 3, so the value "Yellow " can be selected using index 3.

selectByValue

This method selects the dropdown option by its value. We provide a string value as the value as an argument. It possesses the following syntax:

selectByValue(String arg0) : void

If we consider the same dropdown on page "https://demoqa.com/select-menu", as in the previous section, we can see that each of the options of the dropdown has an assigned value as shown below:

How to select value from drop-down list in selenium webdriver

Now, if we have to select the option "White", we can use its value "6 ", as shown in the following code snippet:

// Create object of the Select class Select se = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']"))); // Select the option with value "6" se.selectByValue("6");

As the value "6 " corresponds to the option "White," so it will select the value "White" from the dropdown.

selectByVisibleText

This method enables one to select one option from the dropdown or multi-select dropdown based on the dropdown text. You need to pass the String value of the <select> element as an argument. It possesses the following syntax:

selectByVisibleText(String arg0): void

If we consider the same dropdown on page "https://demoqa.com/select-menu", as in the previous section, we can see that each of the options of the dropdown will have a text value, which is displayed on the web page also, so we can use that text to select the corresponding option, as shown below:

// Create the object of the Select class Select se = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']"))); // Select the option using the visible text se.selectByVisibleText("White");

As the dropdown has one of the options having the text as "White", the same will be selected using the above code.

Apart from the dropdown types briefed above, the HTML <select> tag also provides ways to define dropdowns, which allows selecting multiple values. Let's see how a Multi-Select dropdown will be declared and how we can select multiple options in a dropdown using the "Select " class of Selenium WebDriver.

How to select multiple values from a dropdown in Selenium?

If the <select > tag contains multiple attributes, it means that the dropdown allows selecting multiple values. As we can see in the following screenshot from the web page "https://demoqa.com/select-menu":

How to select value from drop-down list in selenium webdriver

We can use any of the methods we used to select one value from the dropdown to select multiple values by invoking the methods multiple times for different values. The "Select " class provides a method, isMultiple(), using which we can first validate whether the dropdown allows us to select multiple values. Let's see how to use the isMultiple() method:

How to check whether dropdown is Multi-Select?

As we discussed, the Select class provides the "isMultiple() " method, which determines whether the web element in say supports multiple selections. It returns a boolean value, i.e., True/False, without taking any argument. It checks the attribute 'multiple'in the HTML code for the web element. Consequently, it possesses the following syntax:

isMultiple(): boolean

Once you determine whether the web element is multi-select or not, you can use the Select class's various select methods on the multiple values you intend to select. The below example code shows the same-

Select oSel = new Select(driver.findElement(By.xpath(//*[@id='cars']); if(oSel.isMultiple()){ //Selecting multiple values by index oSel.selectByIndex(1); oSel.selectByIndex(2); //Or selecting by values oSel.selectByValue("volvo"); oSel.selectByValue("audi"); //Or selecting by visible text oSel.selectByVisibleText("Volvo"); oSel.selectByVisibleText("Opel"); }

And that is how you can select multiple values from a multi-select dropdown.

Now that we have understood how we can select values from a dropdown, be it single-select or multi-select, we should have some way to check which values the dropdown contains and what all values are selected in the dropdown. The "Select " class provides methods to get options from the dropdown. Let's understand the details and usage of these methods:

How to get options from a dropdown in Selenium?

As highlighted by marker 2, in the image under the "Select " class section above, the Select class provides the following methods to get the options of a dropdown:

  • getOptions()
  • getFirstSelectedOption()
  • getSelectedOptions()

Let's understand the details of all these methods:

getOptions

There are times when you need to get all the options in a dropdown or multi-select box. This is where you can use the getOptions() method of the Select class. It possesses the following syntax:

getOptions(): List<WebElement>

As we can see, this method returns all the options of the dropdown as a list of WebElement. The following code snippet shows how we can get all the options of the dropdown on the page "https://demoqa.com/select-menu":

Select select = new Select(driver.findElement(By.id("oldSelectMenu"))); // Get all the options of the dropdown List<WebElement> options = select.getOptions();

Using this method, we can retrieve all the options of a dropdown (be it single-select or multi-select ).

getFirstSelectedOption()

This method returns the first selected option of the dropdown. If it is a single-select dropdown, this method will return the selected value of the dropdown, and if it is a multi-select dropdown, this method will return the first selected value of the dropdown. It possesses the following syntax:

getFirstSelectedOption(): WebElement

As we can see, this method returns a WebElement. The following code snippet shows how we can get the first selected option of the dropdown on the page "https://demoqa.com/select-menu":

Select select = new Select(driver.findElement(By.id("oldSelectMenu"))); // Get the first selected option of the dropdown WebElement firstSelectedOption = select.getFirstSelectedOption();

Using this method, we can retrieve the first selected option of a dropdown (be it single-select or multi-select ).

getAllSelectedOptions()

This method returns all the selected options of the dropdown. If it is a single-select dropdown, this method will return the only selected value of the dropdown, and if it is a multi-select dropdown, this method will return all the selected values of the dropdown. It possesses the following syntax:

getAllSelectedOptions():List<WebElement>

As we can see, this method returns a list of WebElements. The following code snippet shows how we can get all the selected options of the dropdown on the page "https://demoqa.com/select-menu":

Select select = new Select(driver.findElement(By.id("oldSelectMenu"))); // Get all the selected option of the dropdown List<WebElement> selectedOptions = select.getAllSelectedOptions();

Using this method, we can retrieve all the selected options of a dropdown (be it single-select or multi-select ).

How to deselect a value from a dropdown in Selenium?

Just like we select values in a DropDown & Multi-Select,we can deselect the values too. But the deselect method works only for Multi-Select. You can deselect pre-selected options from a Multi-select element using the different deselect methods discussed here. As we would have observed in the screenshot showing methods of the "Select " class (shown by marker 3), the Select class provides the following methods to deselect values of a dropdown:

  • deselectAll()
  • deselectByIndex()
  • deselectByValue()
  • deselectByVisibleText()

Let's understand the details and usage of all these methods:

deselectAll

This method will clear all the selected entries of the dropdown. It possesses the following syntax:

deselectAll(): void

If there are few options already selected in a dropdown, you can deselect all the options using the method deselectAll().The following code snippet shows a sample example, how we deselect all the values from the dropdown:

Select select = new Select(driver.findElement(By.id("oldSelectMenu"))); //Deselect all the options select.deselectAll();

It will deselect all the options from the dropdown.

deselectByIndex

Similar to the selectByIndex() method, the Select class also provides the method to deselect an option from the dropdown using the deselectByIndex() method. You can use the option's index number to deselect it. It possesses the following syntax:

deselectByIndex(int arg0): void

So, if there are few options already selected in a dropdown, you can deselect one of the options using the method deselectByIndex(). The following code snippet shows a sample example, how we deselect one of the values from the dropdown by specifying its index:

Select select = new Select(driver.findElement(By.id("oldSelectMenu"))); //Deselect first value by index select.deselectByIndex(1);

It will deselect the option at index 1 in the dropdown.

deselectByValue

Similar to the selectByValue() method, the Select class also provides the method to deselect an option from the dropdown using the deselectByValue() method. You can use the option's value to deselect it. It possesses the following syntax:

deselectByValue(String arg0): void

So, if there are few options already selected in a dropdown, you can deselect one of the options using deselectByValue(). The following code snippet shows a sample example, how we deselect one of the values from the dropdown by specifying its value:

Select select = new Select(driver.findElement(By.id("oldSelectMenu"))); //Deselect option with value "6" select.deselectByValue("6");

It will deselect the option with value in the dropdown.

deselectByVisibleText

Similar to the selectByVisibleText() method, the Select class also provides the method to deselect an option from the dropdown using the deselectByVisibleText() method. You can use the option's text to deselect it. It possesses the following syntax:

deselectByVisibleText(String arg0): void

So, if there are few options already selected in a dropdown, you can deselect one of the options using the method deselectByVisibleText(). The following code snippet shows a sample example, how we deselect one of the values from the dropdown by specifying its text:

Select select = new Select(driver.findElement(By.id("oldSelectMenu"))); //Deselect option with text "White" select.deselectByVisibleText("White");

It will deselect the option with the text "White " in the dropdown.

How to select a value from a static dropdown in Selenium?

Software TestingAutomation TestingSelenium Web Driver



The various methods available under Select class in Selenium to select a

value from a static dropdown. They are as listed below −

  • selectByVisibleText(String args)

    This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values.

    Syntax −

    Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByVisibleText("Selenium");
  • selectByIndex(String args)

  • This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values.

  • Syntax −

    Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByIndex(1);
  • selectByValue(String args)

    This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values.

    Syntax −

    Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByValue(“Testing”);

Selenium WebDriver- Handling drop-downs

In this section, you will learn how to handle drop-downs in Selenium WebDriver.

Before proceeding with this section, let us first understand some of the basics of handling drop-downs in Selenium WebDriver.

Select in Selenium WebDriver

The 'Select' class in Selenium WebDriver is used for selecting and deselecting option in a dropdown. The objects of Select type can be initialized by passing the dropdown webElement as parameter to its constructor.

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.

2. selectByValue - It is used to select an option based on its 'value' attribute.

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

Let us consider a test case in which we will automate the following scenarios:

  • Invoke Google Chrome Browser
  • Open URL: https://www.testandquiz.com/selenium/testing.html
  • Select the option "Database Testing" from the drop-down menu
  • Close the browser

We will create our test case step by step in order to give you a complete understanding of how to handle drop-downs in WebDriver.

Step1. Launch Eclipse IDE and open the existing test suite "Demo_Test" which we have created in earlier sessions of this tutorial.

Step2. Right click on the "src" folder and create a new Class File from New > Class.

How to select value from drop-down list in selenium webdriver

Give your Class name as "Dropdwn_Test" and click on "Finish" button.

How to select value from drop-down list in selenium webdriver

Step3. Let's get to the coding ground.

  • To invoke Google Chrome browser, we need to download the ChromeDriver.exe file and set the system property "Running test on Chrome Browser" to the path of your ChromeDriver.exe file. We have already discussed this in earlier sessions of this tutorial. You can also refer to "Running test on Chrome Browser" to learn how to download and set System property for Chrome driver.

Here is the sample code to set system property for Chrome driver:

  • After that we have to initialize Chrome driver using ChromeDriver Class.

Here is the sample code to initialize Chrome driver using ChromeDriver class.

Combining both of the above code blocks, we will get the code snippet to launch Google Chrome browser.

  • After that we need to write the code which will automate our second test scenario (navigate to the desired URL).

Here is the sample code to navigate to the desired URL:

The complete code till now will look something like this:

Step4.Now we will try to locate the drop-down menu by inspecting its HTML codes.

Follow the steps given below to locate the drop-down menu on the sample web page.

  • Open URL: https://www.testandquiz.com/selenium/testing.html
  • Right click on the drop-down menu on the sample web page and select Inspect Element
How to select value from drop-down list in selenium webdriver
  • It will launch a window containing all the specific codes involved in the development of the drop-down menu.
How to select value from drop-down list in selenium webdriver
  • Take a note of its id attribute.
How to select value from drop-down list in selenium webdriver

Step5. To automate our third test scenario, we need to write the code which will select the option "Database Testing" from the drop-down menu.

Here is the sample code to so that:

The following screenshot shows the Eclipse window for our test script.

How to select value from drop-down list in selenium webdriver

Step6. Right click on the Eclipse code and select Run As > Java Application.

How to select value from drop-down list in selenium webdriver

Upon execution, the above test script will launch the Chrome browser and automate all the test scenarios.


Next TopicWebDriver- Drag and Drop



← prev next →



How to handle Dropdown in Selenium by Value or Index?


We can also choose an option by using its index or value attribute. For example, the following option has value attribute “su” and text label “Sunday”.

In HTML coding, we can write it as:

<option value = "su">Sunday</option>

To choose this option by value, we need to call selectByValue() method of the select class by using the object reference variable of select class, as shown in the following line of code:

select.selectByValue("su");

Similarly, another way to choose an option is by using its index. When options in the list are displayed on the web page, they are indexed in the order in which they are defined on the web page.

By specifying an index value in the selectByIndex() method, we can choose an option from the list. The following code is as follows:

select.selectByIndex(2);

Let’s choose the dropdown option by its value attribute in the same scenario. Follow all the above steps as explained in the following source code.

Program source code 2:

package seleniumProject; 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 SelectByValueExample { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); String URL = "https://selenium08.blogspot.com/2019/11/dropdown.html"; driver.get(URL); // Wait for some time to load the whole web page. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate dropdown element on web page by By.xpath. WebElement dropdown = driver.findElement(By.xpath("//select[@name='country']")); // Create an object of Select class and pass the dropdown of type WebElement as an argument. Select select = new Select(dropdown); // Select the option "USA" by sending its value attribute. select.selectByValue("US"); System.out.println("Option is successfully selected"); // Close the browser. driver.close(); } }Output: Option is successfully selected

The same option “USA” in the list can also be selected by using its index like this:

select.selectByIndex(233);

How to select Multiple values in Dropdown using Selenium Webdriver?


In this section, we will deal with the multiple-choice list. We will use is.Multiple() method to verify the multiple options are selected or not in the list.

The isMultiple() method of select class will return true if the dropdown list supports the multi-selection and false if it does not.

Let’s see the source code to verify it.
Program source code 3:

package seleniumProject; 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 multiple-choice { public static void main(String[] args) { WebDriver driver; driver = new FirefoxDriver(); driver.manage().window().maximize(); String URL = "https://selenium08.blogspot.com/2019/11/dropdown.html"; driver.get(URL); // Wait for some time to load the whole web page. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate dropdown element on web page by By.xpath. WebElement dropdown = driver.findElement(By.xpath("//select[@name='Month']")); // Create an object of Select class and pass the dropdown of type WebElement as an argument. Select multiplechoicelist = new Select(dropdown); // Verify that dropdown allows the multiple-choice list or not. if(multiplechoicelist.isMultiple()) { System.out.println( "Dropdown allows multiple-choice list"); } else { System.out.println("Dropdown does not allow multiple-choice"); } // Now select the different choice by using visible text. multiplechoicelist.selectByVisibleText("July"); multiplechoicelist.selectByVisibleText("May"); multiplechoicelist.selectByVisibleText("March"); // Verify that the number of choices in the list selected. if(multiplechoicelist.getAllSelectedOptions().size() == 3) { System.out.println("3 options have been chosen"); } else { System.out.println("Code not worked"); } driver.close(); } }Output: Dropdown allows multiple-choice list 3 options have been chosen

How to get Selected values from Dropdown in Selenium?


In this section, we will learn how to get all the selected values from the multiple-choice list. To get selected values from the multiple-choice list, we will use a method getAllSelectedOptions() of select class.

The getAllSelectedOptions() method will return all selected options as a list of WebElement.

In this test, we will create a list of selected expected items by using add() method of the List interface, and then selected options returned by the getAllSelectedOptions() will be retrieved in a list by iterating WebElement.

Now let us see the following source code related to it. Follow all the above steps and further steps in the following source code.

Program source code 4:

package seleniumProject; import java.util.ArrayList; import java.util.List; 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 GetAllSelectedOptions { public static void main(String[] args) { WebDriver driver; driver = new FirefoxDriver(); driver.manage().window().maximize(); String URL = "https://selenium08.blogspot.com/2019/11/dropdown.html"; driver.get(URL); // Wait for some time to load the whole web page. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate dropdown element on web page by By.xpath. WebElement dropdown = driver.findElement(By.xpath("//select[@name='Month']")); // Create an object of Select class and pass the dropdown of type WebElement as an argument. Select multiplechoicelist = new Select(dropdown); // Verify that dropdown allows the multiple-choice list or not. if(multiplechoicelist.isMultiple()) { System.out.println( "Dropdown allows multiple-choice list"); } else { System.out.println("Dropdown does not allow multiple-choice"); } // If multiple-choice allow, select the different choice by sending visible texts. multiplechoicelist.selectByVisibleText("July"); multiplechoicelist.selectByVisibleText("May"); multiplechoicelist.selectByVisibleText("March"); // Verify that the number of choices in the list selected. if(multiplechoicelist.getAllSelectedOptions().size() == 3) { System.out.println("3 options have been chosen:"); } else { System.out.println("Code not worked"); } // Create a List. For this, create an object of ArrayList class by using the reference of List interface. List<String> expectedSelection = new ArrayList<String>(); // Call add() method of List to add expected elements for selection. expectedSelection.add("July"); expectedSelection.add("May"); expectedSelection.add("March"); // Iterating WebElement by using the advanced for loop to retrieve the actually selected elements and then add selected elements in the list using add() method. List<String> actualSelection = new ArrayList<String>(); for(WebElement element : multiplechoicelist.getAllSelectedOptions()) { actualSelection.add(element.getText()); // Here, getText() method of WebElement class has been used to add the text label of all the options in the list. } // Now compare actualSelection with expectedSelection by using containsAll() method to check that correct options are selected in the list.. if(actualSelection.containsAll(expectedSelection)) { System.out.println(actualSelection); } driver.close(); } }Output: Dropdown allows multiple-choice list 3 options have been chosen: [March, May, July]

Selecting Values from Dropdown using Selenium WebDriver

Steven Roger

0 4,250 3 minutes read

How to select value from drop-down list in selenium webdriver
How to select value from drop-down list in selenium webdriver

In this article, you will study how to select values from dropdown in Selenium WebDriver. Before moving ahead with this tutorial, first let us understand some of the basics of handling drop-downs in Selenium WebDriver.

Video liên quan