
XPath is one of the most widely used locators in Selenium for identifying elements in a web page’s DOM structure. It allows testers to create flexible and precise queries to locate elements based on their attributes, text, or hierarchy. However, when web elements are dynamic and their attributes change frequently, static XPath expressions often fail to identify them accurately.
Dynamic XPath helps overcome this challenge by allowing the use of functions, conditions, and patterns to adapt to element changes in real time. It provides a more resilient way to locate elements whose IDs, names, or classes are dynamically generated, making automation scripts stable even when the web application’s structure evolves.
This article explains what dynamic XPath is, how to create and optimize it in Selenium, and the best practices for using it effectively.
XPath (XML Path Language) is a query language used to locate elements and attributes in an XML or HTML document. In Selenium, it acts as a powerful locator to identify web elements when IDs or class names are unreliable. XPath can traverse the DOM tree in multiple directions, allowing testers to locate elements with complex or nested structures.
XPath supports two main types of expressions: absolute and relative. Absolute XPath defines a complete path from the root element, while relative XPath starts from any node in the document, making it more flexible and preferred in most test automation scenarios. For example, the following command locates any text input field regardless of its position in the DOM.
//input[@type='text']
By combining XPath functions, operators, and conditions, testers can handle web pages with dynamic structures or elements that don’t have stable identifiers. This flexibility makes XPath an essential tool in Selenium testing, especially for dynamic and data-driven web applications.
Static XPath is used to locate elements with attributes or structure that remain constant across sessions. It is simple, reliable, and works well for web pages with a stable DOM. For example:
//button[@id='submit']
This expression always points to the same element as long as the id value does not change. However, when attributes such as id, name, or class are dynamically generated, static XPath often fails to locate the element accurately.
Dynamic XPath solves this problem by using partial matches, conditions, or functions to identify elements even when their attributes vary. For example:
//button[contains(@id, 'submit')]
This expression can locate any button whose ID includes the term submit, such as submit_001 or submit_btn. Dynamic XPath provides the flexibility required for automating modern, data-driven web applications with frequently changing DOM structures.
Dynamic XPath allows testers to build flexible locators that adapt to changing element properties. Before creating one, it is essential to understand the key XPath functions and operators that make expressions dynamic.
Identify attributes or structural relationships that are least likely to change. Prefer visible text, stable attribute fragments, nearby static siblings, or element hierarchy instead of full absolute paths. For example:
Example XPath candidates
//input[contains(@id, 'email')]
//button[text() = 'Submit']
//div[@class='form-row']//label[text() = 'Phone']/following-sibling::input
Build the simplest expression that uniquely identifies the element and test it in the browser before using it in scripts. Use browser DevTools console commands such as $x("<xpath>") or the Elements panel search to confirm a single match. When combining conditions, prefer and for precision and contains() or starts-with() for tolerance. If multiple attributes help, combine them for accuracy.
For example:
WebElement email = driver.findElement(By.xpath("//input[contains(@id, 'email') and @type='email']"));
email.sendKeys("test@example.com");

Dynamic XPath expressions use functions, operators, and conditions that make locators resilient against attribute or structure changes. They allow testers to target elements using partial matches, logical conditions, or text-based relationships rather than fixed attribute values.
Step 1: Use XPath functions to handle variable attributes
When element attributes change dynamically, XPath functions such as contains(), starts-with(), and text() help maintain stability.
//input[contains(@id, 'username')]
//button[starts-with(@name, 'submit')]
//a[text()='Learn More']
Step 2: Combine multiple conditions for precision
To ensure uniqueness and accuracy, conditions can be combined with logical operators such as and or or.
//input[@type='text' and contains(@placeholder, 'email')]
//button[contains(@id, 'login') or contains(@name, 'signin')]
Step 3: Use relational and hierarchical axes for complex structures
When elements lack direct identifiers, XPath axes like parent, child, following-sibling, and ancestor help navigate relationships.
//label[text()='Password']/following-sibling::input
//div[@class='form-container']//ancestor::form[@id='loginForm']
Step 4: Apply indexing for repeated elements
When multiple similar elements exist, indexes ensure the correct one is targeted.
(//button[contains(@class, 'submit')])[2]
Optimizing XPath improves both test speed and reliability. Inefficient locators can slow down execution and increase the risk of failures, especially in complex or dynamic web pages. The following practices help create faster and more maintainable XPath expressions:
Well-structured dynamic XPath expressions improve test stability, reduce maintenance, and ensure scripts remain reliable across frequent UI changes. The following best practices help create XPath locators that perform consistently under real-world test conditions:
Dynamic web elements often appear, disappear, or change their attributes based on user actions or asynchronous updates. These changes can cause Selenium tests to fail if locators are not designed to handle such variations.
Here’s how to handle dynamic web elements in Selenium:
Testing dynamic XPath on real devices ensures that locators remain accurate across varying browsers, operating systems, and screen configurations. Modern web applications render elements differently depending on device type and viewport size. These variations can affect how dynamic attributes, such as element IDs or CSS classes, are generated and displayed.
To achieve this level of accuracy, Selenium tests should be executed on a reliable cloud-based testing platform like BrowserStack Automate. It provides access to thousands of real browsers and devices, allowing dynamic XPath expressions to be verified across multiple configurations without maintaining local infrastructure.
BrowserStack Automate also enables parallel test execution, detailed debugging logs, and seamless integration with CI/CD pipelines, ensuring that your XPath locators remain robust in real-world scenarios.
Dynamic XPath is essential for automating modern web applications where elements frequently change due to dynamic rendering or responsive layouts. By learning to build adaptable locators using functions, conditions, and axes, testers can create automation scripts that remain stable across multiple UI updates and asynchronous events.
To validate these locators in real-world environments, running tests on real devices through BrowserStack Automate ensures complete coverage and consistent results. It enables testing across thousands of real browsers and operating systems without managing physical infrastructure, helping teams deliver high-quality, cross-platform user experiences.
Run Selenium Tests on Cloud
Get visual proof, steps to reproduce and technical logs with one click
Continue reading
Try Bird on your next bug - you’ll love it
“Game changer”
Julie, Head of QA
Try Bird later, from your desktop