Usage of Selenium Select Class for Handling Dropdown Elements on a Web Page – Selenium Tutorial #13

In the previous tutorial, we studied about the various types of assert statements available in Java based unit testing framework and their applications with specimens. Re-iterating the fact that being an “Automation Test Engineer”, assertions play a very decisive and significant role in developing test scripts.

Moving ahead with the few upcoming tutorials in the Selenium series, we would concentrate on handling the various types of web elements available on the web pages. Therefore, in this tutorial, we would consider “dropdowns” and exercise their handling strategies.

Before moving towards problem statement and its resolution, let us take a moment to introduce and create an understanding regarding the application under test. As a sample, we have created a dummy HTML page consisting of multiple and assorted web elements.

The elementary web elements those constitute the web page are:

  • Hyperlink
  • Button
  • Dropdown

Please take a reference of the following webpage aforementioned above:

Selenium select class 1

Explanation of Application under Test

We have designed the web page in a way to include a few fundamental types of web elements.

  • Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs the user to “https://www.google.co.in/” and “http://www.abodeqa.com/” respectively on the click event.
  • Dropdown: The three dropdowns have been created for selecting colors, fruits and animals with a value already set to default.
  • Button: A “try it” button has been created to show up the pop up box having Ok and Cancel button upon click event.

Subsequent is the HTML code used to create the above mentioned webpage:

 <!DOCTYPE html>
<html>
<head><title> Testing Select Class </title>
<body>
<div id="header">
<ul id="linkTabs">
<li>
<a href="https://www.google.co.in/">Google</a>
</li>
<li>
<a href="http://abodeqa.wordpress.com/">abodeQA</a>
</li>
</ul>
</div>
<div class="header_spacer"></div>
<div id="container">
<div id="content" style="padding-left: 185px;">
<table id="selectTable">
<tbody>
<tr>
<td>
<div>
<select id="SelectID_One">
<option value="redvalue">Red</option>
<option value="greenvalue">Green</option>
<option value="yellowvalue">Yellow</option>
<option value="greyvalue">Grey</option>
</select>
</div>
</td>
<td>
<div>
<select id="SelectID_Two">
<option value="applevalue">Apple</option>
<option value="orangevalue">Orange</option>
<option value="mangovalue">Mango</option>
<option value="limevalue">Lime</option>
</select>
</div>
</td>
<td>
<div>
<select id="SelectID_Three">
<option value="selectValue">Select</option>
<option value="elephantvalue">Elephant</option>
<option value="mousevalue">Mouse</option>
<option value="dogvalue">Dog</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
confirm("Press a button!");
}
</script>
</body>
</html>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html> 

Scenario to be automated

  • Launch the web browser and open the webpage
  • Click on the “Google” hyperlink
  • Navigate back to the original web page
  • Select the “Green” in color dropdown
  • Select the “Orange” in the fruit dropdown
  • Select the “Elephant” in the animal dropdown

WebDriver Code using Selenium Select Class

Please take a note that, for script creation, we would be using “Learning_Selenium” project created in the former tutorial.

Step 1: Create a new java class named as “HandlingDropDown” under the “Learning_Selenium” project.

Step 2: Copy and paste the below code in the “HandlingDropDown.java” class.

Below is the test script that is equivalent to the above mentioned scenario:

 import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

/**
 * class description
 */

public class HandlingDropDown {
       WebDriver driver;

       /**
        * Set up browser settings and open the application
        */

       @Before
       public void setUp() {
              driver=new FirefoxDriver();
             
// Opened the application
              driver.get("file:///F:/Work/Blogs/testingstuff/DemoWebAlert.html");
              driver.manage().window().maximize();
       }

       /**
        * Test to select the dropdown values
        * @throws InterruptedException
        */

       @Test
       public void testSelectFunctionality() throws InterruptedException { 
             
// Go to google
              driver.findElement(By.linkText("Google")).click();
             
// navigate back to previous webpage
              driver.navigate().back();
              Thread.sleep(5000);
             
// select the first operator using "select by value"
              Select selectByValue = new Select(driver.findElement(By.id("SelectID_One")));
              selectByValue.selectByValue("greenvalue");
              Thread.sleep(5000);
             
// select the second dropdown using "select by visible text"
              Select selectByVisibleText = new Select (driver.findElement(By.id("SelectID_Two")));
              selectByVisibleText.selectByVisibleText("Lime");
              Thread.sleep(5000);
             
// select the third dropdown using "select by index"
              Select selectByIndex = new Select(driver.findElement(By.id("SelectID_Three")));
              selectByIndex.selectByIndex(2);
              Thread.sleep(5000);       
       }

       /**
        * Tear down the setup after test completes
        */

       @After
       public void tearDown() { 
              driver.quit();
       }
} 

Code Walkthrough

Import Statements


  • import org.openqa.selenium.support.ui.Select – Import this package prior to the script creation. The package references to the Select class which is required to handle the dropdown.

Object Instantiation for Select class

Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));

We create a reference variable for Select class and instantiate it using Select class and the identifier for the drop down.

The identifier or the locator value for the drop down can be found using the techniques discussed in the initial tutorials (by using Selenium IDE and firebug).

Take a notice that the identifier for a dropdown can be found as below:

Step 1: Most or almost all the dropdowns elements are defined in the <Select> tag having multiple values (values that can be set into the dropdown) that are defined under the <option> tags.

Selenium select class 2

Setting the value in the dropdown using selectByValue() method

selectByValue.selectByValue(“greenvalue”);

In the above java command, we select the value “green” in the drop down using the selectByValue() method and parameterizing it with the text present in the value attribute.

Selenium select class 3

Setting the value in the dropdown using selectByVisibleText() method

selectByValue.selectByVisibleText(“Lime”);

In the above java command, we select the value “Lime” in the drop down using the selectByVisibleText() method and parameterizing it with the text present on the user interface or the text present between the opening and closing <option> tags.

Selenium select class 4

Setting the value in the dropdown using selectByIndex() method

selectByValue.selectByIndex(“2”);

In the above java command, we select the third value in the drop down using the selectByIndex() method and parameterizing it with the index value of the element which is desired to be selected in the dropdown.

Take a note that the index value starts with “0”.

Conclusion

In this tutorial, we tried to make you acquainted with the WebDriver’s Select class that is used to handle dropdown elements present on the web page. We also briefed you about the methods that can be used to populate the value in the dropdown.

Here is the article summary:

  • WebDriver’s Select class is used to handle the dropdown elements present on a web page.
  • Prior to the actual scripting, we need to import a package to be able to create a WebDriver script for handling a dropdown and making the Select class accessible.
    • import org.openqa.selenium.support.ui.Select;
  • We create a reference variable for Select class and instantiate it using Select class and the identifier for the drop down.
    • Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
  • The identifier or the locator value for the drop can be found using Selenium IDE and firebug.
  • Ideally there are three ways to select the desired value in the dropdown amongst the listed one.
    • selectByValue()
    • selectByVisibleText()
    • selectByIndex()
  • The following java command is used to select the “green” color in the dropdown. Take a notice the value in the dropdown is selected using the selectByValue()
    • selectByValue(“greenvalue”);
  • The following java command is used to select the “Lime” fruit in the dropdown. Take a notice the value in the dropdown is selected using the selectByVisibleText()
    • selectByVisibleText(“Lime”);
  • The following java command is used to select the third value amongst all the available options enlisted for the dropdown. Take a notice the value in the dropdown is selected using the selectByIndex()
    • selectByIndex(“2”);

Next Tutorial #14: In the forthcoming tutorial, we would discuss about various types of commands in WebDriver like isSelected(), isEnabled() and isDispalyed() those return a Boolean value against the presence of a specified web element.

Till then, stay tuned and automate the dropdown using WebDriver utility – “Select class”.




Recommended reading

21 comments ↓

#1 Henk Noppe

is it same process for other elements as well like radio options etc?

#2 Shruti Shrivastava

@Henk

Select class is primarily used to handle elements with tags.

#3 Abadhesh

Hi Shruti,

Code is not working for me, This is getting terminated automatically as soon as i click on run.

Console Window:

[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@cf768c: 31 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@bb4df8: 0 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@1bc1ae4: 0 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@160847b: 31 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@7f7052: 0 ms

#4 Abadhesh

FAILED: testSelectFunctionality
java.lang.NullPointerException
at TestNG.HandlingDropDown.testSelectFunctionality(HandlingDropDown.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

#5 Nishant Aggarwal

@Abhadesh
The above code is written using Junit, and you are trying to run it with TestNG.
Import below mentioned file in your code & remove Junit.
It will surely run.
import org.testng.annotations.*

#6 Annonymous

What if i can’t found any option value ?

#7 Naveen

This this article you have mentioned selectByIndex(“2?); this may be typo. Mention this as selectByIndex(2); without double courts. because if double courts it take as String, instead of take it as int

#8 Raj N

Hello everyone,

I used “makemytrip” website In my example. which really helps you in understanding and more confidence when you execute the code..
scenario:
1) open the website ‘makemytrip’
2) click on ‘FAQs’ link to navigate to FAQs page and navigate back to Home page.
3) Now select “Premium Class ” Option in the Class dropdown of main page.
4) select “Business” Option from the Class drop down
5) Again Select ” Premium class” Option from the drop down.

this code works in Googlechrome and also internetexplorer which requires 2 lines of code change .. if any one wants to execute in chrome and IE please reply.. so that i can send the code.

Here is the code which works fine in Firefox and with testNG( I have used testNG instead of Junit)

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
* class description
*/

public class HandingDropdown {
WebDriver driver;
/**
* Set up browser settings and open the application
*/
@BeforeMethod
public void setUp() {
driver=new FirefoxDriver();
// Open the application
driver.get(“http://www.makemytrip.com/”);
driver.manage().window().maximize();
}
/**
* Test to select the dropdown value
* @throws InterruptedException
*/
@Test
public void testSelectFunctionality() throws InterruptedException {
// Go to FAQs Page and navigate back to main Page
driver.findElement(By.linkText(“FAQs”)).click();
Thread.sleep(1000);
driver.navigate().back();
Thread.sleep(5000);
// select the Premium option from the drop down using “select by value”
Select selectByValue = new Select(driver.findElement(By.id(“class_selector”)));
selectByValue.selectByValue(“PE”);
Thread.sleep(5000);
// select the Business option from the dropdown using “select by visible text”
Select selectByVisibleText = new Select (driver.findElement(By.id(“class_selector”)));
selectByVisibleText.selectByVisibleText(“Business”);
Thread.sleep(5000);

// select the Premium option from the dropdown using “select by index”

Select selectByIndex = new Select(driver.findElement(By.id(“class_selector”)));
selectByIndex.selectByIndex(1);
Thread.sleep(5000);
}
// You can uncomment below code only if you want to close the browser after execution.
// @AfterTest
// public void tearDown() {

// driver.quit();

// }
}

#9 userselinium

Hi Shruti, I am not able to select element from a dropdown. Can you pls help?

My code is:
IWebElement element = driver.FindElement(By.Id(“header_Menu1Container”));
SelectElement se = new SelectElement(element);
se.SelectByValue(“Add New Action`enter code here`”);

and I tried using selectByText as well.

HTML code:


Actions

#10 Agate

Hello,
How can I select an option from the dropdown using Salinium IDE please?!
I need to select following item from the list: Mother

Many Thanks

#11 Manjushri Jadhav

Hi,

The Scenario is as below:

1. I have web page.

2. On web page i have one dropdown list

3. From dropdown list i have selected one value

So how i can identify which value is selected from dropdown list.

( Interviewer asked me this question recently )

Thanks.

#12 Manjushri Jadhav

Hi,

The Scenario is as below:

1. I have web page.

2. On web page i have one dropdown list

3. From dropdown list i have selected one value

So how i can identify which value is selected from dropdown list.

( Interviewer asked me this question recently )

Thanks.

#13 yogesh bendke

Please send me solution to select from chosen dropdown..i need code for selenium web driver written in java,
my html code is


Select an Option

Organisation Node

#14 Shashi

Hi All,
I am getting Error “Exception in thread “main” org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been “select” but was “input”
Build info: version: ‘2.48.2’, revision: ’41bccdd’, time: ‘2015-10-09 19:55:52’
System info: host: ‘dluaaror524987’, ip: ‘10.207.101.69’, os.name: ‘Windows 7’, os.arch: ‘amd64’, os.version: ‘6.1’, java.version: ‘1.7.0_40′
Driver info: driver.version: unknown
at org.openqa.selenium.support.ui.Select.(Select.java:47)
at Makemytrip.main(Makemytrip.java:30)

————————-
Below is my Script – where i want to select Value in “From” field on make my trip .com-import junit.framework.Assert;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Makemytrip {

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub

WebDriver driver =new FirefoxDriver();
//Launch Make my trip site
driver.get(“http://makemytrip.com”);
driver.manage().window().maximize();
//verify Make my trip appearing at caorrect loacation
Assert.assertTrue(driver.findElement(By.xpath(“.//*[@id=’chf_header’]/div[1]/div/div[1]/p/a[1]”)).isDisplayed());
System.out.println(driver.findElement(By.xpath(“.//*[@id=’chf_header’]/div[1]/div/div[1]/p/a[1]”)).isDisplayed());
System.out.println(driver.findElement(By.xpath(“.//*[@id=’widget_row’]/div[1]/div/div[3]/div/div[1]/h1/span”)).getText());
//make sure one way radio button appers selected
driver.findElement(By.xpath(“.//*[@id=’one_way_button1′]/span”)).click();
System.out.println(driver.findElement(By.xpath(“.//*[@id=’one_way_button1′]”)).isSelected());
//driver.findElement(By.xpath(“.//*[@id=’from_typeahead1′]”)).clear();
driver.findElement(By.xpath(“.//*[@id=’from_typeahead1′]”)).click();
Thread.sleep(3000);

//Select dropdown=new Select(driver.findElement(By.xpath(“.//*[@id=’from_typeahead1′]”)));
Select dropdown=new Select(driver.findElement(By.id(“from_typeahead1”)));
dropdown.selectByValue(“Mumbai, India (BOM)”);
dropdown.selectByVisibleText(“Mumbai, India (BOM)”);
//dropdown.selectByVisibleText(“Bangalore, India (BLR)”);
driver.findElement(By.xpath(“.//*[@id=’start_date_sec’]/span[3]”)).click();
driver.findElement(By.xpath(“//*[@id=’ui-datepicker-div’]/div[2]/table/tbody/tr[5]/td[4]/a”)).click();
driver.findElement(By.xpath(“.//*[@id=’flights_submit’]”)).click();
}

}

#15 Gaurav Khurana

Thanks for taking time for creating a HTML file first. It worked easily.

I did not used the below line
import static org.junit.Assert.*;
I think it was not having significance, is it ? if so can you add that too.

Thanks Raj for sharing that exmaple of makemytrip thats interesting assignment.

Also our aim is to select elephant which is at position number 1. So index should be 1 not 2.
selectByIndex.selectByIndex(1);

i think we should have pressed that button too. :)

#16 kumar

Hi

I used “makemytrip” website In my example. And using drop down listbox.

1) Open the website ‘makemytrip’
2) Click on ‘FAQs’ link to navigate to FAQs page and navigate back to Home page.
3) Select “Business” Option from the Class drop down.

this code works in chrome :

package Inter;

import java.util.concurrent.TimeUnit;

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 DiffBrowChrome {
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”,”E:\\selenium\\Chromedrivers\\chromedriver.exe”);
WebDriver driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(“http://www.makemytrip.com/flights/”);

driver.findElement(By.xpath(“//span”)).click();
driver.navigate().back();
WebElement e1=driver.findElement(By.id(“class_selector”));
Select s1=new Select(e1);
// s1.selectByIndex(2);
s1.selectByValue(“PE”);

String str=driver.getTitle();
System.out.println(str);
}

}

#17 navneet

why did we use ” Thread.sleep(5000);” in code?

#18 Balvindar

how to automate “search text box” using selenium?? can anybody help

#19 anita

how to read zero’th element from dropdown list

#20 Ruchi Gupta

There is a mistake in code walkthrough. You have used SelectByValue in all three cases.

selectByValue.selectByVisibleText(“Lime”);
selectByValue.selectByIndex(“2”);

Shoudn’t it be as in the code ?

selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex.selectByIndex(2);

Thanks,
Great tutorials.You have our blessings for sharing knowledge with us.

#21 sijo jose

Am using selectByIndex method wherein am unable to select the element. But am able to get the index value.

Leave a Comment