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

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.

System.out.println("Product names with length more than eight characters:- ");

// Iterating the list

for(WebElement product:allProductNames)

{

//Extracting text

StringproductName=product.getText().trim();

System.out.println(productName);

}

// Closing browser

driver.quit();

}

}

Output:-

1

2

3

4

5

6

7

Product names with length more than eight characters:-

Faded ShortSleeveT-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

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