0
0
Selenium Javatesting~3 mins

Why XPath functions (contains, starts-with) in Selenium Java? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a few smart XPath tricks can save you hours of tedious clicking!

The Scenario

Imagine you are testing a website with hundreds of buttons and links. You need to find a button that has a label starting with 'Submit' or contains the word 'Next'. Doing this by clicking and checking each element manually is like searching for a needle in a haystack.

The Problem

Manually checking each element is slow and tiring. You might miss some buttons or click the wrong ones. It's easy to make mistakes, and repeating this every time the page changes wastes a lot of time.

The Solution

XPath functions like contains() and starts-with() let you write smart queries to find elements by partial text or attributes. This means you can quickly and accurately select the right elements without checking each one manually.

Before vs After
Before
driver.findElement(By.xpath("//button[text()='Submit Form']"));
After
driver.findElement(By.xpath("//button[starts-with(text(),'Submit')]");
driver.findElement(By.xpath("//a[contains(text(),'Next')]");
What It Enables

With these XPath functions, you can easily find elements even if their text changes slightly, making your tests more flexible and reliable.

Real Life Example

On a shopping site, the 'Add to Cart' button might say 'Add to Cart Now' or 'Add to Cart - Limited Offer'. Using starts-with() or contains() helps your test find the button no matter the exact text.

Key Takeaways

Manual element search is slow and error-prone.

XPath functions contains() and starts-with() simplify locating elements by partial text.

These functions make tests more flexible and easier to maintain.