9u. WebDriver – Selecting items in two ways (Dropdowns and multiple selections)

Hiya rockstars (guitar and music not included though)! In this post, we delve into dropdowns and how to select items in two ways. And yes, we also talk about multiple selections! All concepts will be explained along with examples from our Demo Site.

Method 1:

Using the same age old traditional way of locating elements using one of the available locating strategies. First, we find the dropdown element and then locate the required item to select. This is little difficult as the options have no unique identifiers.

Example: Let us locate ‘Programming Languages’ dropdown by its id. To locate ‘C++’ from the available dropdown items, we will have to find all the elements with tag name ‘options’ and get it in a list. Iterate through the list or if its index is known, retrieve the elements accordingly and perform click action.

Right clicking on required elements and selecting inspect element gives corresponding HTML code which is as below,

<select id="programming-languages" class="input-xlarge" name="languages">
			<option value="Java">Java</option>
			<option value="C++">C++</option>

Code:

// Locate 'Programming Languages' dropdown using id
WebElement progLanguages = driver.findElement(By.id("programming-languages"));
//Get all options in a list
List<WebElement> options = progLanguages.findElements(By.tagName("option"));
//Iterate thorough options
for (WebElement option : options) {
	if("C++".equals(option.getText()))
	option.click();
}

(OR)

WebElement progLanguages = driver.findElement(By.id("programming-languages"));
List<WebElement> options = progLanguages.findElements(By.tagName("option"));
//Selecting “C++” based on its index
options.get(1).click();

Here 0, 1, 2, 3 are index values of the dropdown.

Method 2: Using ‘Select’ class.

Let us delve in and understand how Select class works and see if it is magical by any chance. And why would you want to use this in the first place?

Using method 1 has a major disadvantage. Selecting a specific option becomes very difficult as they have no unique identifiers. Also, to select multiple options, deselect a particular item, it gets complicated. Selenium webdriver once again comes to our rescue! It provides Select class with pre-defined methods specially for handling dropdowns and multiple selection scenarios.

Step 1: This select class is available in “org.openqa.selenium.support.ui.Select” package. Hence it is mandatory to import this package in our test script.

import org.openqa.selenium.support.ui.Select;

Step 2:  Create an instance for the Select class by passing required dropdown identifier.

Select languages = new Select(driver.findElement(By.id("element_ID")));

Any of the previously discussed locating strategies (http://94.143.139.145/selenium/9j-webdriver-locating-elements-1/) can be used to locate the dropdown.

Step 3: Once the dropdown web element is located and an object for Select class is created, all its methods can be accessed to perform selection and deselection.

Sticky Note:

Select class works only for web elements that have <select> tags.

Below is a snapshot of all the methods available in Select class.

Select class methods

There are a lot of essentials to discuss and juggle here. Let us distil some of the commonly used methods with examples and code snippets.

Sticky Note:

You might bump into NoSuchElementException with all select and deselect methods in case no matching options are found.

1. selectByVisibleText(String arg0) and deselectByVisibleText(String arg0)

These methods select and deselect an option with the displayed text that matches exactly with the passed String argument.

Syntax: selectObject.selectByVisibleText(“displayed_option_text”);

selectObject.deselectByVisibleText(“displayed_option_text”);

Example: Let us select ‘JavaScript’ from Programming Languages dropdown.

Code: (To select)

// Locate 'Programming Languages' dropdown using id
WebElement languagesDD = driver.findElement(By.id("programming-languages"));
// Create an instance of 'Select' class by passing the dropdown web element
Select languages = new Select(languagesDD);
// Select 'JavaScript' language by its visible text
languages.selectByVisibleText("JavaScript");

(To deselect)

languages.deselectByVisibleText("JavaScript");

2. selectByValue(String arg0) and deselectByValue(String arg0)

These methods select and deselect an option whose value attribute matches the passed String argument.

Syntax: selectObject.selectByValue(“value_attribute_text”);

selectObject.deselectByValue(“value_attribute_text”);

Example: Let us select ‘Selenium RC’ from Selenium Tool Suite multi selection options.

Right clicking on the required web element and selecting inspect element gives corresponding HTML code which is as below,

<select id="selenium_suite" multiple="multiple" name="selenium_suite">
	<option value="IDE">Selenium IDE</option>
	<option value="WebDriver">Selenium WebDriver</option>
	<option value="RC">Selenium RC</option>

The value of the ‘value’ attribute, “RC” is to be passed as the argument to the selectByValue method.

Code:

multiSelect.selectByValue("RC");

3. selectByIndex(int arg0) and deselectByIndex(int arg0)

These methods select and deselect an option at the specified index value. It is important to note that the index value always starts with zero.

Syntax: selectObject.selectByIndex(“option_index”);

selectObject.deselectByIndex (“option_index”);

Example: Let us deselect ‘Selenium RC’ from Selenium Tool Suite multi selection options.

Based on the HTML code, Selenium IDE has index 0, Selenium WebDriver has index 1 and Selenium RC has index 2.

Code:

multiSelect.deselectByIndex(2);

4. deselectAll()

This method clears the selection. No argument is passed.

Sticky Note:

This method works only for multi select scenarios i.e. <select> tag should have a multiple attribute with value as “multiple”. Otherwise it throws “NotImplementedError”.

Syntax: selectObject.deselectAll()

Example: Let us deselect all the options selected in the Selenium Tool Suite multi select box.

Code:

multiSelect.deselectAll();

5. isMultiple()

This method comes handy when you wish to know if the web element allows multi selection or not. It returns either true or false. No arguments are passed.

Syntax: selectObject.isMultiple()

6. getOptions()

This method returns a list of all the options available in the multi selection box as web elements.

Syntax: selectObject.getOptions()

Code:

List<WebElement> allOptions = multiSelect.getOptions();

7. getFirstSelectedOption()

This method returns the first selected option in a multi selection box. If this is used on a dropdown where only a single selection is allowed, then the selected option is returned as a web element.

Syntax: selectObject.getFirstSelectedOption().getText()

This returns the option text that is selected.

8. getAllSelectedOptions()

This method returns a list of all the options that are selected as part of a multi selection box as web elements.

Syntax: selectObject.getAllSelectedOptions()

Code:

List<WebElement> allSelectedOptions = multiSelect.getAllSelectedOptions();

Overall picture

Let us see a test case implementing all the actions covered in this post so far,

Scenario

  1. Open Firefox browser
  2. Navigate to the demo site
  3. Locate ‘Programming Languages’ dropdown using id
  4. Create an object for Select class
  5. Select ‘JavaScript’ language by its visible text
  6. Print the selected option to the console
  7. Check if ‘Programming Languages’ dropdown supports multiple selection and print the corresponding message to console
  8. Locate ‘Selenium Tool Suite’ multi select box using name
  9. Create an instance of the Select class with multi-select web element
  10. Select ‘Selenium RC’ and ‘Advantages’ by their value
  11. Deselect ‘Selenium RC’ by its index
  12. Select ‘Selenium WebDriver’ by its visible text
  13. Get all the selected options in a list and print them to the console
  14. Verify Eclipse IDE console output screen and JUnit pane for success result

JUnit code for this scenario is,

package com.blog.junitTests;
import java.util.List;
import java.util.concurrent.TimeUnit;

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.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SelectItems {
	// Declaring variables
	private WebDriver driver;
	private String baseUrl;

	@Before
	public void setUp() throws Exception {
		// Selenium version 3 beta releases require system property set up
		System.setProperty("webdriver.gecko.driver", "E:\\ Softwares\\"
			+ "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
		// Create a new instance for the class FirefoxDriver
		// that implements WebDriver interface
		driver = new FirefoxDriver();
		// Implicit wait for 5 seconds
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		// Assign the URL to be invoked to a String variable
		// baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
		baseUrl = "file:///E:/Chandu/My%20Blog/githubDemoSite/index.html";
	}

	@Test
	public void testPageTitle() throws Exception {
		// Open baseUrl in Firefox browser window
		driver.get(baseUrl);
			
		// Locate 'Programming Languages' dropdown using id
		WebElement languagesDD = driver.findElement(By.id("programming-languages"));
		// Create an instance of 'Select' class by passing the dropdown web element
		Select languages = new Select(languagesDD);
		// Select 'JavaScript' language by its visible text
		languages.selectByVisibleText("JavaScript");
		// Prints the selected option to console
		System.out.println("Selected programming language is: " + languages.getFirstSelectedOption().getText());
		// Check if languages dropdown supports multiple selection and print the result to console
		if(languages.isMultiple()){
			System.out.println("Languages dropdown supports multiple selection");
		}else {
			System.out.println("Languages dropdown does not support multiple selection");
		}

		// Locate multi select element using name
		WebElement toolSuite = driver.findElement(By.name("selenium_suite"));
		// Create an instance of 'Select' class by passing the multi select element
		Select multiSelect = new Select(toolSuite);
		// Select 'Selenium RC' by its value
		multiSelect.selectByValue("RC");
		// Select 'Advantages' by its value
		multiSelect.selectByValue("Adv");
		// De-select 'Selenium RC' by its index
		multiSelect.deselectByIndex(2);
		// Select "Selenium WebDriver" by its visible text
		multiSelect.selectByVisibleText("Selenium WebDriver");
		// Get all selected options in a list
		List<WebElement> suiteItems = multiSelect.getAllSelectedOptions();
		// Prints all selected options
		System.out.println("Options selected  under 'Selenium Tool Suite' are:");
		for (WebElement option : suiteItems) {
			System.out.println(option.getText());
		}
		
	} // End of @Test

	@After
	public void tearDown() throws Exception {
		// Close the Firefox browser
		driver.close();
	}
}

Execution Result:

Each line of code is accompanied with self-explanatory comments as well as parts of the code are explained as part of each concept covered in the post.

In JUnit window, green bar shows that the test case is executed successfully. Console window shows the absence of any errors. It also shows all the printed messages as expected.

select items eclipse output

Below image shows the Firefox output obtained upon successful execution of the test script.

select items firefox output

This concept is not so hard to wrap your heads around. So get going and practice a huge lot. I will see you soon in another post. Have a great day!

4 Comments 9u. WebDriver – Selecting items in two ways (Dropdowns and multiple selections)

  1. Ajay

    Is there a way to find the element of a page inside a loop?

    driver.findElement(By.xpath(SEARCH_INPUT_FIELD)).sendKeys(DYNAMIC_VALUE); driver.findElement(By.xpath(SEARCH_INPUT_FIELD)).sendKeys(Keys.RETURN);

    //dynamic element
    Thread.sleep(1000);
    WebElement selectElement = driver.findElement(By.xpath(DYNAMIC_SELECT_DROPDOWN));
    Select option = new Select(selectElement);
    System.out.println(option.getFirstSelectedOption());

    /*
    If this runs for 5 times, only the 1st time it works properly, next iteration onward the variable ‘option’ is empty.
    But the element ‘selectElement’ is identified properly.
    */

    Thanks!

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

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