Categories: Selenium Topics

Advanced Selenium Concepts – Custom Select Class – Select Value Containing Specific Text in Drop down

Hello Folks,

Most of us we know that to handle a dropdown developed using Select tag, we can use inbuilt class of Selenium named “Select” class. This class provides you three methods to select options in dropdown which are below:

  1. selectByValue – You need to provide exact value to get it selected.
  2. selectByVisibleText – You need to provide exact text to get it selected.
  3. selectByIndex – You must need to know index of desired of desired value.

 

If you want to select any value which contains some specific text, it will not be easy with above methods. I see people create their own special methods to handle this scenarios. But instead of using other ways, we can modify inbuilt functionality of class “Select” itself and use it for our specific scenarios.  So, in this post, I will explain how can we create a new method to select a option containing specific text.

Let’s create a select tag drop down as below:

Select your skill below:

Scenario: Select option which contains “Testing” in drop down.

We know it is not possible using inbuilt methods selectByVisibleText and selectByValue of Select class and selectByIndex will work only if you know the index in advance. Index is not a good option as it will change if new option is added in drop down.

So we will create a new custom method for Select class. I will use concept implemented in actual Select class with modification as required.

package PageObjectModelUsingPageFactory;

import java.util.Iterator;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Quotes;
import org.openqa.selenium.support.ui.UnexpectedTagNameException;

public class CustomSelect {
        
        
        private final WebElement element;
        private final boolean isMulti;

        public CustomSelect(WebElement element) {
                String tagName = element.getTagName();
                if (null != tagName && "select".equals(tagName.toLowerCase())) {
                        this.element = element;
                        String value = element.getAttribute("multiple");
                        this.isMulti = value != null && !"false".equals(value);
                } else {
                        throw new UnexpectedTagNameException("select", tagName);
                }
        }

        public boolean isMultiple() {
                return this.isMulti;
        }




        private void setSelected(WebElement option, boolean select) {
                boolean isSelected = option.isSelected();
                if (!isSelected && select || isSelected && !select) {
                        option.click();
                }

        }

        // Method to select option with containing text
        public void selectByPartialVisibleText(String text) {
                List options = this.element
                                .findElements(By.xpath(".//option[contains(normalize-space(.) , " + Quotes.escape(text) + ")]"));
                boolean matched = false;

                for (Iterator subStringWithoutSpace = options.iterator(); subStringWithoutSpace.hasNext(); matched = true) {
                        WebElement candidates = (WebElement) subStringWithoutSpace.next();
                        this.setSelected(candidates, true);
                        if (!this.isMultiple()) {
                                return;
                        }
                }
                
                if (!matched) {
                        throw new NoSuchElementException("Cannot locate element with text: " + text);
                }

        }

}

Scenario java code:

package HandlingDropdown;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import PageObjectModelUsingPageFactory.CustomSelect;

public class SingleSelectDropdown {

        public static void main(String[] args) throws InterruptedException {
                
                System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
                WebDriver driver= new ChromeDriver();
                driver.get("file:///C:/Users/amodm/Downloads/CustoSelect.html");
                
                // Locating select tag web element
                WebElement singleSelectTagDropdownWebElement= driver.findElement(By.id("SingleDD"));
                
                // Custom select
                        
                CustomSelect selectObject= new CustomSelect(singleSelectTagDropdownWebElement);
                selectObject.selectByPartialVisibleText("Testing");
                
        }
}

Output:

 

We will see some more custom methods in upcoming posts.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Recent Posts

Ways of Handling StaleElementReferenceException Without PageFactory

Hello Folks, Previously, I had published on Handling StaleElementReferenceException using PageFactory. But many people asked how to handle it if they…

4 days ago

How to Verify if Options in Dropdown are Sorted as Expected In Selenium WebDriver – Java

Hello Guys, As I say always, your automation script is ineffective if you do not include logic to validate to…

2 weeks ago

How Much Java Required For Selenium?

"How much Java I need to learn for selenium with Java binding?" is mostly asked question by a Professional who…

3 weeks ago

How To Verify If An Input Box Accepts Only Numbers Through Selenium

Hello Guys, You should not be able to type alphabets or special characters in a field which supposed to accept…

3 weeks ago

How To Verify Maximum Character Limit of an Input Box Through Selenium

Hello Folks, Recently a guy asked me this question which he was asked in an interview in IBM. What the…

3 weeks ago

API Testing Tutorial Part 15 – Sending GET Request With Params in Postman

Hello Folks, As part of our API Testing series, we will see “Sending GET request with params in Postman”. In last…

3 weeks ago