Make Selenium Easy

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:-

With string-length() method:-


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.



Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through 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

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

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

by Amod Mahajan time to read: 2 min
%d bloggers like this: