XPath Method- string-length() – Usage in Locating Element

Hello Guys,

I am going to explain the usage of a method named string-length() from XPath 1.0. This method is very useful to write advanced and dynamic locators.

XPath 1.0 provides an overloaded method named string-length():-

string-length(string) – returns length of given string

string-length() – returns the length of the string specified by the context node.

We can use this method to write xpath for different scenarios. Let’s consider a scenario:-

You search for a product on Amazon and it displays many results. You need to select products whose name has specific count of characters. It may be equals to a number or less than a number or more than a number. For example:- List product names which has a length greater than 5.

Traditional way will be retrieving all names of product and then iterating and filtering as per count of characters in name. Obviously you need to write good more lines of code.

We can use string-length() method to do it at locator level itself. An example is as below:-

I will take a demo website named AutomationPractice. It lists women dresses. I need name of dresses which has more than 8 characters.

Open the developer console and paste below xpath:-

//ul[@class=’product_list grid row’]/li//h5//a[string-length(normalize-space(text()))>8]

I used normalize-space to trim white spaces around text. You can read more about it here.

Using above method you can save a lot of time and unnecessary coding.

Without using string-length method:-

package ScenariosPractice;

import java.util.List;

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

public class WithoutStringLengthMethod {
        

        public static void main(String[] args) {
                
                // Set chrome browser executable path
                System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/chromedriver.exe");

                // Launch chrome
                WebDriver driver = new ChromeDriver();
                
                // Launch URL
                driver.get("http://automationpractice.com/index.php?id_category=3&controller=category");
                
                // Locating all names of product
                List allProductNames= driver.findElements(By.xpath("//ul[@class='product_list grid row']/li//h5//a"));
                
                System.out.println("Product names with length more than eight characters:- ");
                
                // Iterating the list
                for(WebElement product: allProductNames)
                {
                        //Extracting text
                        String productName= product.getText().trim();
                        
                        // Adding condition to check length
                        if(productName.length()>8)
                        {
                                System.out.println(productName);
                        }
                }
                
                // Closing browser
                driver.quit();
                
        }

}

With string-length() method:-

package ScenariosPractice;

import java.util.List;

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

public class WithStringLengthMethod {
        

        public static void main(String[] args) {
                
                // Set chrome browser executable path
                System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/chromedriver.exe");

                // Launch chrome
                WebDriver driver = new ChromeDriver();
                
                // Launch URL
                driver.get("http://automationpractice.com/index.php?id_category=3&controller=category");
                
                // Locating all names of product which has length greater than 8
                List allProductNames= driver.findElements(By.xpath("//ul[@class='product_list grid row']/li//h5//a[string-length(normalize-space(text()))>8]"));
                
                System.out.println("Product names with length more than eight characters:- ");
                
                // Iterating the list
                for(WebElement product: allProductNames)
                {
                        //Extracting text
                        String productName= product.getText().trim();
                        
                        System.out.println(productName);
                        
                }
                
                // Closing browser
                driver.quit();
                
        }

}

Output:-

Product names with length more than eight characters:- 
Faded Short Sleeve T-shirts
Printed Dress
Printed Dress
Printed Summer Dress
Printed Summer Dress
Printed Chiffon Dress

Above is just a scenario. You can use above method in many scenarios as per your need. You can share those scenario in comment to know more people.

Share this post to your colleagues and friends to extend their knowledge.

#ThanksForReading

#ThanksForSharing

Leave a Reply

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