In this tutorial, we will learn how to handle Drop Down and Multiple Select Operations.
Select Option from Drop-Down Box
Before we can control drop-down boxes, we must do following two things:
- Import the package org.openqa.selenium.support.ui.Select
- Instantiate the drop-down box as a "Select" object in WebDriver
As an example, go to Mercury Tours' Registration page (http://www.practiceselenium.com) and notice the "Country" drop-down box there.
Import the "Select" package.
Declare the drop-down element as an instance of the Select class. In the example below, we named this instance as "drpCountry".
We can now start controlling "drpCountry" by using any of the available Select methods. The sample code below will select the option "ANTARCTICA."
Selecting Items in a Multiple SELECT elements
We can also use the selectByVisibleText() method in selecting multiple options in a multi SELECT element. As an example, we will take http://jsbin.com/osebed/2 as the base URL. It contains a drop-down box that allows multiple selections at a time.
The code below will select the first two options using the selectByVisibleText() method.
The following are the most common methods used on drop down list.
Here is the complete code
|Drop-Down Box||selectByVisibleText()/deselectByVisibleText()||selects/deselects an option by its displayed text|
|selectByValue()/ deselectByValue()||selects/deselects an option by the value of its "value" attribute|
|selectByIndex()/ deselectByIndex()||selects/deselects an option by its index|
|isMultiple()||returns TRUE if the drop-down element allows multiple selection at a time; FALSE if otherwise|
|deselectAll()||deselects all previously selected options|
To control drop-down boxes, you must first import the org.openqa.selenium.support.ui.Select package and then create a Select instance.