How to select multiple values in listbox in Selenium WebDriver

Handling Multi Select DropDown in Selenium WebDriver

We will see the following things in this tutorial.

DeSelect values from multi-select dropdown using the following Methods

  • Select values from multi-select dropdown
  • deselectByIndex
  • deselectByValue
  • deselectByVisibleText
  • deselectAll

Select value from dropdown having checkboxes as select option.

Multi-Select Dropdown

We will try to understand the examples by using the following HTML Page.

The HTML source code for the sample page is as follows. Please copy it in a notepad and save the code as an HTML file.

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><h4>Add or remove list items from one list to another </h4>
<HEAD>
<TITLE>Moving the options of one list box to other</TITLE>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<SCRIPT language=javascript>
function addOption_all_list(selectbox){
removeAllOptions(document.drop_list.Category);
addOption(document.drop_list.Category, "PHP","PHP");
addOption(document.drop_list.Category, "ASP","ASP");
addOption(document.drop_list.Category, "JavaScript","JavaScript");
addOption(document.drop_list.Category, "HTML","HTML");
addOption(document.drop_list.Category, "Perl","Perl");
addOption(document.drop_list.Category, "Python","Python");
}
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
function removeOption(listbox,i)
{
listbox.remove(i);
}
function addOption_list(){
for(i=document.drop_list.Category.options.length-1;i>=0;i--) {
var Category=document.drop_list.Category;
if(document.drop_list.Category[i].selected){
addOption(document.drop_list.SubCat, document.drop_list.Category[i].value, document.drop_list.Category[i].value);
removeOption(Category,i);
}
}
}
function move_all_Option(selectbox){
for(i=document.drop_list.Category.options.length-1;i>=0;i--) {
var Category=document.drop_list.Category;
addOption(document.drop_list.SubCat, document.drop_list.Category[i].value, document.drop_list.Category[i].value);
}
removeAllOptions(document.drop_list.Category);
}
function removeAllOptions(selectbox)
{
for(i=document.drop_list.SubCat.options.length-1;i>=0;i--)
{
var SubCat=document.drop_list.SubCat;
addOption(document.drop_list.Category, document.drop_list.SubCat[i].value, document.drop_list.SubCat[i].value);
}
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
//selectbox.options.remove(i);
selectbox.remove(i);
}
}
function remove_list(){
for(i=document.drop_list.SubCat.options.length-1;i>=0;i--) {
var SubCat=document.drop_list.SubCat;
if(document.drop_list.SubCat[i].selected){
addOption(document.drop_list.Category, document.drop_list.SubCat[i].value, document.drop_list.SubCat[i].value);
removeOption(SubCat,i);
}
}
}
</SCRIPT>
<META content="MSHTML 6.00.2900.3395" name=GENERATOR>
<META content="Arachnophilia 4.0" name=FORMATTER></HEAD>
<BODY text=#000000 vLink=#800080 aLink=#ff0000 link=#0000ff bgColor=#ffffff
onload=addOption_all_list() ;>
<FORM name=drop_list action=yourpage.php method=post><INPUT title=addOption_all_list() type=button value="Add All" ;="">
<SELECT multiple size=7 id=language name=Category><OPTION value=PHP>PHP</OPTION><OPTION
value=ASP>ASP</OPTION><OPTION value=JavaScript>JavaScript</OPTION><OPTION
value=HTML>HTML</OPTION><OPTION value=Perl>Perl</OPTION><OPTION
value=Python>Python</OPTION></SELECT>&nbsp;<INPUT title=addOption_list() id="btnMove" type=button value="Move >" ;="">
<INPUT title=move_all_Option() type=button value="Move All >>" ;="">
<SELECT id=SubCat multiple size=7 name=SubCat></SELECT>
<INPUT title=remove_list() type=button value="< Remove" ;="">
<INPUT title=removeAllOptions(SubCat) type=button value="<< Remove All" ;="">
</BODY></HTML>

How to Select Values from Multi-Select DropDown Using Selenium Webdriver

There are two ways to select multiple values from a multi-select dropdown

  1. Select value one by one by using either of the methods visible Text, Value, or by Index of the items.
  2. Using the Action class

Example – Selecting multiple values from dropdown One by One

In the following code, I am selecting the first option of the dropdown using its index and after that, I am selecting value ASP and Python by using selectByVisibleText method.Checkout the following script for better understanding.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 TestMultiSelectDropDown {
public static void main(String[] args) throws InterruptedException {
//Setting the path of Chrome Browser Driver
String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe";
//Setting System property for Chrome browser Driver.
System.setProperty("webdriver.chrome.driver",BrowserDriverPath);
//Create a new Instance for Chrome Browser
WebDriver driver = new ChromeDriver();
//Navigating to multi-select dropdown sample page
driver.get("file:///C:/TestFolder/multi-select-dropdown.html");
WebElement DropDownElement=driver.findElement(By.id("language"));
//Creating Dropdown select object
Select dropdownSelectObject=new Select(DropDownElement);
//Selecting multiple values from dropdown
dropdownSelectObject.selectByIndex(0);
dropdownSelectObject.selectByVisibleText("ASP");
dropdownSelectObject.selectByVisibleText("Python");
driver.findElement(By.id("btnMove")).click();
//close browser
//driver.close();
}
}

Example – Selecting multiple values from dropdown using Action Class

The Action Class will behave in the same way as you will do select multiple options. You will press the Ctrl button from Keyboard and then click on the desired options that you want to select. The approach is as follows.

Create the WebElement object for the desired options that you want to select.

Example:

1
2
3
4
5
6
7
8
9
WebElement option1= driver.findElement(By.xpath("//option[@value='PHP']"));
WebElement option2= driver.findElement(By.xpath("//option[@value='Perl']"));
//Creating action class object
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).click(option1).click(option2).build().perform();
driver.findElement(By.id("btnMove")).click();

The complete code is as follows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class TestMultiSelectDropDown {
public static void main(String[] args) throws InterruptedException {
//Setting the path of Chrome Browser Driver
String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe";
//Setting System property for Chrome browser Driver.
System.setProperty("webdriver.chrome.driver",BrowserDriverPath);
//Create a new Instance for Chrome Browser
WebDriver driver = new ChromeDriver();
//Navigating to multi-select dropdown sample page
driver.get("file:///C:/TestFolder/multi-select-dropdown.html");
//Creating WebElement Object for two options
WebElement option1= driver.findElement(By.xpath("//option[@value='PHP']"));
WebElement option2= driver.findElement(By.xpath("//option[@value='Perl']"));
//Creating action class object
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).click(option1).click(option2).build().perform();
driver.findElement(By.id("btnMove")).click();
//close browser
//driver.close();
}
}

Deselect a Value from a Dropdwon Using deselectByIndex Method

We can use deselectByIndex method to deselect any option using its index beginning from 0.

1
2
3
4
//Deselects second option in the dropdown
dropdownSelectObject.deselectByIndex(1)

A complete example of all select methods has been given at the end of this article.

Deselect a Value from a Dropdwon Using deselectByValue Method

We can use deselectByValue method to deselect any option using value attribute of option tag.

1
2
3
4
//Deselects ASP option
dropdownSelectObject.deselectByValue("ASP")

A complete example of all deselect methods will be given below after discussing all deselect methods.

Deselect a Value from a Dropdwon Using deselectByVisibleText Method

We can use deselectByVisibleText method to deselect any option using the option visible text value.

1
2
3
4
//Deselects Python option
dropdownSelectObject.deselectByVisibleText("Python")

A complete example of all deselect methods will be given below after discussing all deselect methods.

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:

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:

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 "//demoqa.com/select-menu" we have the select the 4th value of the dropdown as highlighted below:

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 "//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:

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 "//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 "//demoqa.com/select-menu":

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 "//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 "//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 "//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.

Video liên quan

Postingan terbaru

LIHAT SEMUA