Understanding XPath Ends With Function

Learn what the XPath ends-with function is, its components, and use cases. Execute XPath queries within Selenium and Appium test scripts running on BrowserStack for cross-browser and real-device testing.

Get Started free
Understanding XPath Ends With Function
Home Guide Understanding XPath Ends With Function

Understanding XPath Ends With Function

Web pages often have interactive elements, such as buttons, input fields, or links, that enhance the user experience. Automation testing allows you to simulate user interactions and validate application behavior. However, many modern web applications contain dynamic elements whose attributes, like id, class, or name, change frequently, often with every page reload or user session.

This constant variation makes it difficult to reliably locate these elements using traditional locators. XPath, with its flexible functions like the Ends With function, provides an efficient solution by allowing testers to identify elements based on partial or changing attribute values.

This article explains what XPath is, its key components, use cases, and how to use it.

What is XPath?

XPath (XML Path Language) is a powerful query language for navigating and locating elements in XML and HTML documents.

XPath in Selenium is one of the most commonly used locators for identifying elements on a webpage when other locators like ID, name, or class are insufficient. XPath traverses the DOM to locate the desired element.

There are two types of Xpath in Selenium:

  • Absolute XPath: It defines the path from the root element to the target element. It’s not recommended due to its dependency on the exact DOM structure, as any small change in the structure can break the XPath.

Example:

/html/body/div[1]/section/div/input
Copied
  • Relative XPath: It helps locate an element based on specific conditions, such as attributes or text, and starts with //. This makes it flexible and less affected by changes in the DOM structure.

Example:

//input[@id='username']
Copied

What is XPath Ends With Function?

The ends-with() function in XPath is used to check if a given string ends with a specific substring. This is especially useful for handling dynamic elements, where attribute values change unpredictably.

It helps identify elements based on the ending portion of their attributes. However, it is available in XPath 2.0 and is not supported by Selenium or Appium, which use XPath 1.0.

Understanding the Syntax of XPath Ends With Function

It’s essential to understand the syntax of the XPath ends-with() function to use it effectively.

Syntax of ends-with() :-

ends-with(string, 'suffix')
Copied

string: The main string to be checked.

suffix: The substring to check at the end of the string.

Returns: true if string ends with suffix, otherwise false.

How does the Ends With Function Compare to Other XPath Functions?

XPath provides various functions to handle string-based conditions when locating elements. Each function serves a unique purpose, such as checking if a string starts, ends, contains specific text, or extracts parts of a string.

FunctionDescriptionExample Xpath
ends-with()Checks if a string ends with a specific substring//button[ends-with(text(), ‘Now’)]
starts-with()Checks if a string starts with a specific substring//input[starts-with(@id, ‘user_’)]
contains()Checks if a string contains a specific substring//div[contains(@class, ‘error’)]
substring()Extracts part of a string based on character position//a[substring(@href, 1, 5) = ‘https’]
string-length()Finds the length of a string//input[string-length(@name) > 5]

Key Components of ends-with() Function in XPath

XPath’s ends-with() function helps locate elements whose attributes or text content conclude with a specific substring. Each component makes XPath queries effective when dealing with dynamic elements.

Below is a breakdown of these components for better clarity.

1. Function Name

The function name is ends-with(). It checks whether a given string ends with a specified substring. It is useful when the goal is to match the ending part of a string rather than the entire string or the beginning portion.

Example:

ends-with(string, 'suffix')
Copied

This checks if the string ends with the provided suffix.

2. Input String

The input string is the primary text or attribute value the ends-with() function evaluates. It can come from a node value, an attribute, or text content. The checks this string to determine whether it ends with the specified substring.

Example Input String (from an attribute):

For the following XML:

<user username="john_doe"/>
Copied

The input string for ends-with() would be john_doe, which is extracted from the username attribute of the <user> element.

3. Substring to Match

The function looks for this substring (or “suffix”) at the end of the input string. If the input string ends with this substring, the function returns true; otherwise, it returns false.

Example:

ends-with(@username, 'doe')
Copied

This function checks if the username attribute, john_doe, ends with doe. If it does, the result is true.

4. Boolean Result

The function produces a Boolean value: true if the input string ends with the specified substring and false otherwise. This can be used in XPath expressions to filter or locate elements based on the condition.

Examples:

  • ends-with(“john_doe”, “doe”) : true

The input string “john_doe” ends with the substring “doe”, so the function returns true.

  • ends-with(“alice_smith”, “doe”) : false

The input string “alice_smith” does not end with “doe”, so the function returns false.

5. XPath Context Node

The context node is the XML/HTML document element on which the ends-with() function operates. It defines the scope in which the function searches for the specified condition.

Example with XML

Given the XML:

<users>

<user username="john_doe"/>

<user username="alice_smith"/>

<user username="michael_doe"/>

</users>
Copied

XPath Query: This query checks the username attribute of all <user> elements to see if they end with doe.

//user[ends-with(@username, 'doe')]
Copied

It Matches:

<user username="john_doe"/>

<user username="michael_doe"/>
Copied

It does not match:

<user username="alice_smith"/>
Copied

Use Cases of XPath ends-with() Function

XPath’s ends-with() function is particularly useful in scenarios where dynamic elements need to be identified based on the ending portion of an attribute or text value. Below are several practical use cases where the ends-with() function proves valuable.

1. Selecting elements based on Attribute values

If you want to locate <product> elements where the category attribute ends with the word electronics, you can use the ends-with() function.

Example XML:

<store>

    <product category="home_electronics" name="Television"/>

    <product category="kitchen_appliances" name="Microwave"/>

    <product category="office_electronics" name="Laptop"/>

    <product category="furniture" name="Sofa"/>

</store>
Copied

Xpath Query:

//product[ends-with(@category, 'electronics')]
Copied

Expected Output:

<product category="home_electronics" name="Television"/>

<product category="office_electronics" name="Laptop"/>
Copied

Explanation: This query finds all <product> elements where the category attribute ends with electronics. It’s especially helpful when you want to filter items based on a portion of their attribute value.

2. Filtering by File Extensions

If you need to select files with a .pdf extension, use the ends-with() function to filter by file type.

Example XML:

<files>

    <file name="report.pdf"/>

    <file name="document.txt"/>

    <file name="invoice.pdf"/>

</files>
Copied

Xpath Query:

//file[ends-with(@name, '.pdf')]
Copied

Expected Output:

<file name="report.pdf"/>

<file name="invoice.pdf"/>
Copied

Explanation: This query selects all <file> elements where the name attribute ends with .pdf, which is useful when working with file lists or directories.

3. Finding Elements with Specific Class Names

If you want to select HTML <button> elements where the class name ends with _submit, you can use the ends-with() function.

Example HTML:

<button class="btn_submit"></button>

<button class="btn_cancel"></button>

<button class="btn_primary"></button>
Copied

XPath Query:

//button[ends-with(@class, ‘btn'_submit')]
Copied

Expected Output:

<button class="btn_submit"></button>
Copied

Explanation: This query selects buttons whose class attribute ends with btn_submit. It helps in targeting specific buttons based on their class suffix.

BrowserStack Automate Banner

4. Text Content Matching

If you want to find elements where the text content ends with a specific word, you can use the ends-with() function.

Example HTML:

<h1>Welcome Home</h1>

<h1>Good Morning</h1>

<h1>Back Home</h1>
Copied

Xpath Query:

//h1[ends-with(text(), 'Home')]
Copied

Expected Output:

<h1>Welcome Home</h1>

<h1>Back Home</h1>
Copied

Explanation: This query selects all <h1> elements whose text content ends with the word Home. It’s useful when filtering elements based on the text.

5. Filtering Dynamic Content

The ends-with () function helps select elements with dynamic IDs or attributes that end with a known pattern.

Example HTML:

<input id="user_123"/>

<input id="user_456"/>

<input id="user_789"/>
Copied

XPath Query:

//input[ends-with(@id, '_789')]
Copied

Expected Output:

<input id="user_789"/>
Copied

Explanation: This query selects the <input> element whose id ends with “_789”. This is helpful when dealing with elements that follow a dynamic ID or pattern.

6. Advanced Search in XML Documents

In XML documents, you can select elements based on nested values where the value ends with a specific word.

Example XML:

<books>

    <book>

        <title>Learning Java</title>

    </book>

    <book>

        <title>Mastering XPath</title>

    </book>

    <book>

        <title>Java for Beginners</title>

    </book>

</books>
Copied

Xpath Query:

//book[ends-with(title, 'Java')]
Copied

Expected Output:

<book>

    <title>Learning Java</title>

</book>
Copied

Explanation: This query selects all <book> elements where the title ends with the word Java. It helps filter out books or items with titles matching specific patterns.

How to Use ends-with() Function in Automation?

Although XPath 2.0 supports the ends-with() function, tools like Selenium and Appium use XPath 1.0. Since ends-with() is not available in XPath 1.0, we need workarounds for such cases. Below are examples for both Selenium and Appium.

1. Working with ends-with() in Selenium

Since Selenium uses XPath 1.0, the ends-with() function is unavailable. However, a workaround using substring() can achieve the same result.

Example HTML:

<input id="login_user_field" type="text">

<input id="register_user_field" type="text">

<input id="admin_username" type="text">
Copied

XPath(Workaround):-

//input[substring(@id, string-length(@id) - string-length('user_field') + 1) = 'user_field']
Copied

Selenium python code

from selenium import webdriver

from selenium.webdriver.common.by import By



# Initialize WebDriver

driver = webdriver.Chrome()



# Open the webpage

driver.get("https://example.com")



# Find element using XPath workaround for ends-with()

element = driver.find_element(By.XPATH, "//input[substring(@id, string-length(@id) - string-length('user_field') + 1) = 'user_field']")



# Perform actions 

element.send_keys("testuser")



# Close the browser

driver.quit()
Copied

Explanation: This workaround checks the end of the id attribute by comparing its substring with user_field, effectively mimicking the ends-with() function.

2. Working with ends-with() in Appium

Appium also uses XPath 1.0, so a substring workaround is needed when selecting elements based on their class or ID that ends with a specific value.

Example: Selecting a Button by Class in a Mobile App

from appium import webdriver



# Set up Appium capabilities

capabilities = {

    "platformName": "Android",

    "deviceName": "emulator-5554",

    "app": "path/to/app.apk"

}



driver = webdriver.Remote("http://localhost:4723/wd/hub", capabilities)



# Find element whose class ends with "_button"

button = driver.find_element(By.XPATH, "//*[substring(@class, string-length(@class) - string-length('_button') + 1) = '_button']")



# Click the button

button.click()



# Close session

driver.quit()
Copied

This will match elements:

<button class="primary_button"></button>

<button class="submit_button"></button>
Copied

This workaround helps identify elements with dynamic class names. It’s especially useful in mobile automation when dealing with buttons or other elements whose class names change dynamically.

Validating XPath Queries on BrowserStack

XPath expressions, including the ends-with function, may behave differently across browsers and mobile platforms. Running tests on a single local setup may not reveal inconsistencies that occur in real-world environments.

BrowserStack provides a cloud-based platform to execute Selenium and Appium test scripts on real browsers and devices to ensure accurate validation of XPath-based element selection.

By integrating BrowserStack into your automation workflow, you can execute Selenium test scripts to validate XPath behavior across multiple browsers (Chrome, Firefox, Edge, Safari, etc.). You can also run Appium-based tests on real mobile devices to verify XPath-based locators.

Here are some key reasons to use BrowserStack to validate XPath Queries.

  • Parallel Testing: Run multiple test scripts simultaneously to speed up XPath validation across different configurations and reduce test execution time.
  • Local Testing: Validate XPath queries on applications hosted in development or staging environments using secure tunneling and ensure accurate testing before deployment.
  • Debugging Tools: Capture screenshots, video recordings, and test logs to inspect XPath failures and identify potential issues in element selection.
  • Interactive DevTools: Access built-in browser developer tools during test execution to inspect elements, test XPath expressions, and troubleshoot selection issues in real-time.
  • Test Observability: Use AI-driven failure root cause analysis and smart reporting to track pass percentage, flakiness percentage, build run time, number of muted days, and other key metrics.

Talk to an Expert

Conclusion

The ends-with() function in XPath 2.0 helps filter elements based on attribute values, text content, and dynamic patterns. However, since Selenium and Appium support only XPath 1.0, workarounds using the substring() function are necessary to achieve similar results.

Execute automation scripts on BrowserStack Automate (for web) or Appium (for mobile) and inspect element selection using session logs, debugging tools, and real-time test execution insights. As testing scales, BrowserStack enables parallel testing, automatic device provisioning, and CI/CD integration to run tests efficiently across real browsers and devices.

Try BrowserStack Now

Useful Resources for Selenium

Methods, Classes, and Commands

Locators and Selectors

Best Practices, Tips and Tricks

Useful Resources for Appium

Tutorials

Best Practices, Tips, and Tricks

Tags
Appium Automation Testing Selenium