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

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated June 23, 2024

In the previous tutorial, we studied 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 will concentrate on handling the various types of web elements available on the web pages. Therefore, in this tutorial, we will consider “dropdowns” and exercise their handling strategies.

Before moving towards the 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 comprising multiple and assorted web elements.

Managing Dropdown Elements on a Webpage

Select Class for Handling Dropdown Elements on a Web Page

The elementary web elements that constitute the web page are:

  • Hyperlink
  • Button
  • Dropdown

Please take a reference to the following webpage afore-mentioned above:

elementary web elements

Explanation of Application Under Test

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

  • Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-direct 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 showed up the pop-up box having OK and Cancel buttons upon click the 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 “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 note that, for script creation, we will be using the “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 before 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 the Select class and instantiate it using the Select class and the identifier for the dropdown.

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 drop down 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 parametrizing 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 parametrising 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 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 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 the Select class and instantiate it using the 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 among the listed ones.
    • 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(“green value”);
  • 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 options enlisted for the dropdown. Take notice the value in the dropdown is selected using the selectByIndex()
    • selectByIndex(“2”);

Next Tutorial #14: In the forthcoming tutorial, we will discuss 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”.

Was this helpful?

Thanks for your feedback!

Recommended Reading

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

  1. 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

    Reply
  2. 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);
    }

    }

    Reply
  3. 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

    Reply
  4. can any one send me the total selenium doc with examples and interview quetion and answers plz.
    ID:kapilkumarreddy69@gmail.com

    Reply
  5. 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();

    // }
    }

    Reply
  6. Hi Shruti,

    Thanks a lot for providing such a detailed knowledge!. In this tutorial, there is no hyperlink to go to previous tutorial for learning the assert statements. Also, where I need to look for the entire series of this course? I wanna start reading from tutorial#1. Please let me know.

    Reply
  7. 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)

    Reply
  8. 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.

    Reply
  9. 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.

    Reply
  10. Kindly provide the solution for the below Error
    “Element should have been “select” but was “button””
    My code to select the drop down field is as below
    Select s1 = new Select(d.findElement(By.id(“drop_projectId”)));
    s1.selectByIndex(1);

    Reply
  11. hi, it’s DEFINITELY helpful. but what if you have dropdown created using anchor tag with select class and you wanted to automate using xpath?

    Reply
  12. 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.

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

    linl: Select an Option
    Organisation Node

    Reply
  14. 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. 🙂

    Reply
  15. 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.

    Reply
  16. Hi All,

    I am doing UI validation with selenium python, after opening the UI in browser will get some options for selecting different hardware’s.

    Scenario 1:

    1. select the hardware
    2.click on next
    3.it will go to next page

    this scenario i did

    scenario 2:

    1. directly want to open second page and need to be click any option.

    2. that also need by using different test method in same class

    If possible can u please provide example code for this scenario.

    Thanks,
    Anusha

    Reply
  17. @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.*

    Reply
  18. 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

    Reply
  19. 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();
    }

    }

    Reply
  20. Hello Team ,
    I have one query for suppose if we have web application where drop down application is at bottom to page .so select class only will work or combination of action class and select class needs to be used

    Reply
  21. Hi Shruthi,
    This was a nice explanation, thank you very much for the blog.
    i have a question:
    Is there any specific order to execute the methods, for ex: i have my below test method code:

    Select byValue=new Select(driver.findElement(By.id(“SelectID_One”)));
    byValue.selectByValue(“greenvalue”);
    Thread.sleep(5000);

    Select byVisibleText=new Select(driver.findElement(By.id(“SelectID_One”)));
    byVisibleText.selectByVisibleText(“Yellow”);
    Thread.sleep(5000);

    Select byIndex=new Select(driver.findElement(By.id(“SelectID_One”)));
    byIndex.selectByIndex(0);
    Thread.sleep(5000);

    Here i am choosing first Green then Yellow then Red but while executing i could see Red color selected then green then yellow.
    i did not understand as it is not selecting as per my code order.

    Can you explain.

    Thanks,
    Charitha

    Reply

Leave a Comment