How To Handle Drop Down in Selenium WebDriver

Dropdown in SeleniumHandling Drop Down in Selenium WebDriver seems so tedious but WebDriver API has gifted us with one class Select. By using this class we can handle Drop Down in Selenium WebDriver quite easily.

If you want to learn more about Selenium WebDriver then I would suggest you read all the articles from Selenium WebDriver page.
So let’s start with small part of HTML code

<select name="height">
<option value="3">3ft</option>
<option value="4">4ft</option>
<option value="5">5ft</option>
<option value="6">6ft</option>
</select>

Open any of the text editors and paste above HTML code and save this file as <name>.htm. We will be using the above HTML file to perform all action on drop down.

If we observe carefully then we will see that the above HTML code is having “select” HTML tag. For such WebElement Selenium has given Select class.

 

Select Class in WebDriver has many methods and function that interacts with Drop Down.
so let see how we should handle drop down

So here is the list of all methods and Constructor that can be used in Selenium WebDriver

Select Class Constructor
Select(WebElement element)

So to initialize its object we need to call it like this

Select select = new Select (WebElement wb)

Here WebElement is an interface defined in Selenium API which extends “SearchText” and “TakeScreenShot” class, which represent HTML element and it provides all the operation to interact with an element on an HTML Page.

Here User is provided with three options to select options from the dropdown.

  • Selecting Dropdown Option using Visible Text: So if we are taking reference from above HTML code then we can see that following are the visible text as a dropdown option
    3ft, 4ft, 5ft and 6ft and if we want to select 5ft option in that case we need to write it like this
    objectOfSelect.selectByVisibleText(“5ft”) So final code would be something like this
select.selectByVisibleText("5ft");

  • Selecting Dropdown Option using Index: In this, we can select the dropdown option using an index. But we need to remember that index of any dropdown starts from 0 so if there are 4 options in any dropdown then there would be following index 0, 1,2,3
    So the index of the first option would be 0 and similarly index of the second option would be 1 and so on and so forth. So if the user wants to select the 2nd option from the dropdown, then he needs to provide the index 1 (Always remember that this method takes int value). So the code will look like this
select.selectByIndex(1);
  • Selecting Dropdown Option using Value: In this, we can select any option, using value attributes value. So if we want to select 4ft in provided HTML. In that case, we need to call value of value attribute and that is 4. So the code will look like this
    select.selectByValue("4");

    At the same time, if we want to validate option selected is correct or not for the same we have one method getFirstSelectedOption() and it will return the detail of selected option and to fetch the text we can call method getText(). So the code would look like

    select.getFirstSelectedOption().getText()

    so above line of code will return the text of select dropdown option and If you want to learn about the assertion in Selenium then I would suggest you, read these two post
    How to use assertEquals() in WebDriver using driver.getText()

    assertTrue(message,condition) in Selenium WebDriver and it’s implementation

 

@Test
	public void test()
	{
	driver.get("C:/Users/kaushal/Desktop/Size_DropDown.htm");
	/*to get options of drop down we would use name=height attribute that is given in above code

	*/
	Select select = new Select(driver.findElement(By.name("height")));
	//finding the number of option using size() function
	int i =select.getOptions().size();
	//printing the size
	System.out.print("number of options ="+i);
	//verifying number of option is 4
	assertEquals(4, select.getOptions().size());
	// selecting option in Drop-down using Visible Text
	select.selectByVisibleText("5ft");
	assertEquals("5ft", select.getFirstSelectedOption().getText());

	//selecting option in Drop-down using value attribute
	select.selectByValue("4");
	assertEquals("4ft", select.getFirstSelectedOption().getText());

	//selecting option in Drop-down using value attribute
	select.selectByIndex(1);
	assertEquals("4ft", select.getFirstSelectedOption().getText());

	/*verifying the options of drop down first we would put all value in one list and then we would add all value fetched from instance of Select Class that we have used before in code in another array list and then we would verify the value*/
	//first string type list that would contain all option value
	List list = Arrays.asList(new String[]{"3ft",
	"4ft", "5ft","6ft"});
	List  list1 = new ArrayList();
	//adding all option captured by select in to list1 arraylist
	for(WebElement element:select.getOptions())
	{
	list1.add(element.getText());
	}
	//to see what is being added to arraylist use this code
	int j = list1.size();
	System.out.println("value entered in J ="+j);
	for(int k = 1; k<j; k++)
	{
	System.out.println(list1.get(k));
	}
	Assert.assertArrayEquals(list.toArray(), list1.toArray());

	}

Similarly, the “Select” class has an equal number of methods to deselect the option from the dropdown.

1- DeselectAll: this option is used to deselect all options selected in dropdown. Here is code

select.deselectAll();

2. DeselectByVisibleText: This option is used to deselect selected option using visible text and this can be used like this.

// to deselect 5ft option using visible text
select.deselectByVisibleText("5ft");

3. DeselectByIndex: This method is used to deselect the selected option using the index.

//this method will take int as argument
select.deselectByIndex(2);

4. DeselectByValue:  This method is used to deselect the selected dropdown option using the value of the value attribute.

select.deselectByValue("5");

 

Before exiting from this post, Check how good you are in Selenium WebDriver by taking this Selenium WebDriver Quiz.

Above code has used JUnit Testing framework. But above code, you can use in Java Main and Using TestNG as well.

 

Dwarika Dhish Mishra

My name is Dwarika Dhish Mishra, its just my name and I am trying to bring the worth of my name in to actions and wants to be the solution not the problem. I believe in spreading knowledge and happiness. More over I am fun loving person and like travelling a lot. By nature I am a tester and a solution maker. I believe in the tag line of http://ted.org “Idea worth spreading” . For the same, I have created this blog to bring more and more learning to tester fraternity through day to day learning in professional and personal life. All contents are the part of my learning and so are available for all..So please spread the contents as much as you can at your end so that it could reach to every needful people in testing fraternity. I am pretty happy that more and more people are showing interest to become the part your Abode QA blog and I think this is good sign for us all because more and more content would be before you to read and to cherish. You may write or call me at my Email id: dwarika1987@gmail.com Cell: 9999978609

You may also like...

17 Responses

  1. Anshu says:

    Hi Dwarika,

    Thanks for the post but while i was using above example , i am getting an error message as “The method assertEquals(int, int) is undefined for the type GoogleSuggest” where GoogleSuggest is the name of the class.
    Can you please suggest something on this?

  2. satish says:

    Hi,
    I’m getting an error message as”The method assertEquals(int, int) is undefined for the type DropDown” where DropDown is the name of the Class….
    I’m waiting for your valuable suggestions???????

  3. This assertion error so I would request that just count the number of drop- down manual and then use

    assertEquals(“your value that you have counted”, select.getOptions().size());

    Here

    select.getOptions().size() gives the number of options available in dropdown.

    Steps to handle dropdown
    1- Move to drop-down
    2- Right click and inspect the element without selecting any option from the drop-down
    3- Now find the xpath either by yourself or just do right click and click on Copy Xpath
    4- put it in to

    Select select = new Select(driver.findElement(By.xpath(“you xpath”))
    5- Now find the number of option by using
    select.getOptions.size(); and compare this with actual number

    Hope this will make it clear to understand the handling of drop down.

  4. Roopesh says:

    hi will u plz help me how can i enter mobile number into a text field having “Mobile Mask” using Webdriver.

    Ref link:http://www.musiczeal.com/musician-registration.aspx
    click on “Telephone Text field”

    Thanks in Advance

  5. sun pat says:

    Use the as usual sendkeys method to enter phone number like –

    driver.findElement(By.id(“ctl00_mainbody_txtPhone1”)).sendkeys(“”1234567890);

    Try if it works!

  6. Eshan says:

    Hi,
    Just wanted to thank you for all contributions, using ruby and selenium
    Eshan
    Canada – Toronto

  7. christian says:

    Hello,

    Please i need help i’m new in seleniumwebdriver!!!
    How can i handle this situacion in a dropdown with ul class:

    this is my code:
    driver.findElement(By.xpath(OR.getProperty(“//*[@id=’search-filter-facet-categoryId’]/div/div/div”))).sendKeys(listcatg);

    listcatg is take it from doc.xls. where listcatg = Prendas superiores

    Categoría
    Prendas superiores
    Prendas inferiores

    Code:

    Categoría

    Prendas superiores

    Prendas inferiores

    thank so much
    Kriss

    • christian says:

      Categoría

      Prendas superiores

      • christian says:

        CODE of url>
        ul class=”facet-fields”
        li
        div id=”search-filter-facet-categoryId” class=”search-filter search-filter-list active” data-input-value=”” data-input-type=”standard” data-input-name=”categoryId”
        div class=”custom-select-list”
        div class=”search-filter-content”
        div class=”search-filter-wrapper”
        span class=”search-filter-label” data-property=”GLB_CATEGORY”>Categoría
        Prendas superiores

  8. Rohit says:

    Hi..
    I want to konw how to handle drop down which contains arrow button. After clicking on arrow button again one list comes out and I want to select one option amonga them.
    Can you please give me solution for this ASAP.

    Thanks and Regards
    Sourabh Chanchawat

  9. manivannan says:

    how do compare the more than 100 drop down list values…

    • Mohan says:

      Get those elements in List and compare it,

      WebElement select = findElement(lctr1);
      List listElements = select.findElements(lctr2);

      List li = new ArrayList();
      for(int k=0;k<li.size();k++){
      li.add(listElements.get(k).getText().trim();
      }

  10. pgadwala says:

    I wanted to know how to work on drop down using DIV and LI with no select and no options if possible using with loops. As I have tried this .
    //Enter the Data set Name
    driver.findElement(By.xpath(“//div[@id=’displayfield-1032-inputEl’]”)).sendKeys(“Carrefour Finished Goods*”);
    Thread.sleep(2000);

    • Yes, it is possible to do this.

      Steps:
      1- Find a generic xpath or css selector or any of the locator that can select all element
      2- Take all these elements in list
      3- Iterate in to list and match with the string that you want to select
      4- It will help you to select one of the options from complete list under dropdown those are started with div or li
      Thanks
      Dwarika

  11. allwin says:

    What are the possible ways to handle drop down which is not mentioned with select class.
    Drop down is listed under . Tried xpath but it isnt working.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.