Selenium-Select-CLass Notes By ShariqSP

Dropdown Menu

A dropdown menu, also known as a select menu or a select box, is a graphical control element that allows users to choose one value from a list of options. It typically appears as a box with a downward-facing arrow next to it. When clicked, the box expands to display a list of options, and the user can select one option from the list.

To create a dropdown menu in HTML, you use the <select> element along with its nested <option> elements. Here's a basic example:

                    
            <label for="country-select">Select a Country:</label>
            <select id="country-select">
                <option value="USA">United States</option>
                <option value="CAN">Canada</option>
                <option value="MEX">Mexico</option>
            </select>
                    
                

In this example, we have a dropdown menu with three options: United States, Canada, and Mexico. The value attribute of each <option> element represents the value that will be submitted to the server when the form containing the dropdown menu is submitted. The text between the opening and closing <option> tags is what the user sees in the dropdown menu.

You can add more options to the dropdown menu by adding additional <option> elements inside the <select> element. You can also specify default selected options, disabled options, or group related options using the <optgroup> element.

Select Class in Selenium

Introduction

We can't handle dropdowns directly in Selenium WebDriver. To interact with dropdowns, we use the Select class.

The Select class provides methods for selecting and deselecting options in a dropdown.

Methods of Select class

                    
                        void selectByIndex()
                        void selectByVisibleText()
                        void selectByValue()
                        void deselectByValue()
                        void deselectByVisibleText(String text)
                        void deselectAll()
                        WebElement getFirstSelectedOption()
                        List<WebElement> getAllSelectedOption()
                        List<WebElement> getOptions()

What is Select Class in Selenium?

In Selenium, the Select class provides the implementation of the HTML SELECT tag. A Select tag provides the helper methods with select and deselect options. As Select is an ordinary class, its object is created by the keyword New and also specifies the location of the web element.

How to use Select Class in Selenium?

Selenium offers Select Class which can be used to select value in the dropdown list. There are different methods in the Select Class which can be used to perform different actions in the dropdown element. It allows you to select the option based on its text, index, and value, select multiple options, or deselect all.

Code Examples


            

---------------------selectByxPath-------------------------------------

System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); ChromeDriver driver = new ChromeDriver(); driver.get("https://demowebshop.tricentis.com/"); driver.manage().window().maximize(); driver.findElement(By.xpath("//a[@href='/books']")).click();

---------------------selectByIndex-------------------------------------

selectByIndex: selectByIndex(int arg0) : void WebElement ele = driver.findElement(By.id("products-orderby")); Select s = new Select(ele); s.selectByIndex(1);

----------------------selectByValue-------------------------------------

selectByValue: selectByValue(String arg0) : void WebElement ele = driver.findElement(By.id("products-pagesize")); Select s = new Select(ele); s.selectByValue("https://demowebshop.tricentis.com/books?pagesize=4");

---------------------selectByVisibleText-------------------------------

selectByVisibleText: selectByVisibleText(String arg0): void WebElement ele = driver.findElement(By.id("products-viewmode")); Select s = new Select(ele); s.selectByVisibleText("List");

---------------------select multiple-----------------------------------

driver.get("https://demoapp.skillrary.com/"); driver.manage().window().maximize(); WebElement ele = driver.findElement(By.id("cars")); Select s = new Select(ele); s.selectByIndex(3); s.selectByIndex(1); s.selectByIndex(4);

---------------------get first selected options-------------------------

System.out.println(s.getFirstSelectedOption().getText());

---------------------get all select options-----------------------------

List<WebElement> list = s.getAllSelectedOptions(); for(WebElement ele1 : list) System.out.println(ele1.getText());

---------------------get all options------------------------------------

getOptions: getOptions( ) : List<WebElement> List<WebElement> list1 = s.getOptions(); for(WebElement ele1 : list1) System.out.println(ele1.getText());

Problem Statement: Finding Duplicates in a Dropdown Menu

You have a webpage with a dropdown menu containing a list of countries. You want to find out if there are any duplicate entries in the list of countries.

Solution: Java Program using Selenium WebDriver

Below is a Java program that uses Selenium WebDriver to automate the process of extracting country names from the dropdown menu, counting occurrences of each country, and identifying any duplicates.

                    
            import org.openqa.selenium.By;
            import org.openqa.selenium.WebDriver;
            import org.openqa.selenium.WebElement;
            import org.openqa.selenium.chrome.ChromeDriver;
            import java.util.List;
            import java.util.ArrayList;
            import java.util.HashMap;
            import java.util.Map;
            
            public class FindDuplicatesInDropdown {
                public static void main(String[] args) {
                    // Set the path to ChromeDriver executable
                    System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
            
                    // Initialize Chrome WebDriver
                    WebDriver driver = new ChromeDriver();
            
                    // Open the webpage
                    driver.get("file:///path/to/your/html_file.html"); // Replace with the path to your HTML file
            
                    // Find the dropdown element
                    WebElement dropdown = driver.findElement(By.id("country-select"));
            
                    // Get all options from the dropdown
                    List<WebElement> options = dropdown.findElements(By.tagName("option"));
            
                    // Extract country names from options
                    List<String> countryNames = new ArrayList<>();
                    for (WebElement option : options) {
                        countryNames.add(option.getText());
                    }
            
                    // Count occurrences of each country
                    Map<String, Integer> countryCounts = new HashMap<>();
                    for (String country : countryNames) {
                        countryCounts.put(country, countryCounts.getOrDefault(country, 0) + 1);
                    }
            
                    // Find duplicates
                    List<String> duplicates = new ArrayList<>();
                    for (Map.Entry<String, Integer> entry : countryCounts.entrySet()) {
                        if (entry.getValue() > 1) {
                            duplicates.add(entry.getKey());
                        }
                    }
            
                    // Output duplicates
                    if (!duplicates.isEmpty()) {
                        System.out.println("Duplicates found:");
                        for (String duplicate : duplicates) {
                            System.out.println(duplicate);
                        }
                    } else {
                        System.out.println("No duplicates found.");
                    }
            
                    // Close the WebDriver
                    driver.quit();
                }
            }
                    
                

Select Class Interview Questions

  1. What is the purpose of the Select class in Selenium WebDriver?
  2. How do you create an instance of the Select class in Selenium?
  3. Explain the difference between selectByValue, selectByVisibleText, and selectByIndex methods in the Select class.
  4. How do you deselect an option in a dropdown using the Select class?
  5. What exceptions can occur while using the Select class methods?
  6. Explain the getOptions() method in the Select class.
  7. How do you retrieve the selected option from a dropdown using the Select class?
  8. What is the purpose of isMultiple() method in the Select class?
  9. Explain the selectByVisibleText() method in the Select class.
  10. How do you deselect all options from a dropdown using the Select class?
  11. What is the difference between selectByValue and selectByIndex methods?
  12. Explain the deselectByValue() method in the Select class.
  13. How do you get all selected options from a multi-select dropdown using the Select class?
  14. Explain the deselectByVisibleText() method in the Select class.
  15. How do you check if a dropdown supports multiple selections using the Select class?
  16. Explain the deselectAll() method in the Select class.
  17. How do you retrieve all options from a dropdown using the Select class?
  18. Explain the selectByIndex() method in the Select class.
  19. How do you check if an option is selected in a dropdown using the Select class?
  20. Explain the selectByVisibleText() method in the Select class.

Multiple Choice Questions (MCQs)

  1. Which method is used to select an option from a dropdown using its visible text?
    1. selectByVisibleText()
    2. selectByValue()
    3. selectByIndex()
    4. selectByText()
  2. What method is used to deselect all options from a dropdown?
    1. deselectAll()
    2. clearSelection()
    3. deselect()
    4. unselect()
  3. Which method is used to check if a dropdown supports multiple selections?
    1. isMultiple()
    2. supportsMultipleSelections()
    3. hasMultipleOptions()
    4. isMultiSelect()
  4. What method is used to retrieve all options from a dropdown?
    1. getOptions()
    2. retrieveOptions()
    3. fetchOptions()
    4. retrieveAll()
  5. Which method is used to deselect an option from a dropdown using its value?
    1. deselectByValue()
    2. deselectByVisibleText()
    3. deselectByIndex()
    4. unselectByValue()
  6. What method is used to check if an option is selected in a dropdown?
    1. isSelected()
    2. isOptionSelected()
    3. isItemSelected()
    4. isSelectedOption()
  7. Which method is used to retrieve the selected option from a dropdown?
    1. getSelectedOption()
    2. retrieveSelectedOption()
    3. fetchSelectedOption()
    4. getSelected()
  8. What method is used to deselect an option from a dropdown using its index?
    1. deselectByIndex()
    2. unselectByIndex()
    3. deselect()
    4. removeByIndex()
  9. Which method is used to retrieve the first selected option from a dropdown?
    1. getFirstSelectedOption()
    2. retrieveFirstSelectedOption()
    3. fetchFirstSelectedOption()
    4. getFirstSelected()
  10. What method is used to select multiple options from a dropdown?
    1. selectMultipleOptions()
    2. selectMultiple()
    3. selectMultipleItems()
    4. selectMultipleSelections()