Contents

    Guides

    How to Use Dynamic XPath in Selenium: A Complete Guide

    Published on

    November 6, 2025
    How to Use Dynamic XPath in Selenium: A Complete Guide

    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.

    Understanding XPath and Its Role in Selenium

    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 vs Dynamic XPath in Selenium

    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.

    Getting Started with Dynamic XPath in Selenium

    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.

    Step 1: Inspect the element and select stable anchors

    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:

    • Attribute anchor: use parts of an attribute when the full value is dynamic, for example contains(@id, 'login').
    • Text anchor: use text() when the displayed label is stable, for example //button[text() = 'Sign in'].
    • Structural anchor: use a nearby static element as context, for example //label[text() = 'Email']/following-sibling::input.

    Example XPath candidates 

    //input[contains(@id, 'email')]

     //button[text() = 'Submit']

     //div[@class='form-row']//label[text() = 'Phone']/following-sibling::input

    Step 2: Construct and validate the XPath, then integrate into Selenium

    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:

    • Validation example in console: $x("//input[contains(@id, 'email')]") — returns matched nodes.
    • Selenium integration example (Java):

    WebElement email = driver.findElement(By.xpath("//input[contains(@id, 'email') and @type='email']"));

    email.sendKeys("test@example.com");

    • Fallback strategy: if an XPath is brittle, create a secondary locator based on a stable ancestor or a CSS selector for specific cases.

    Creating Dynamic XPath Expressions in Selenium

    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.

    • contains(): Matches any element whose attribute value includes a specific substring.

    //input[contains(@id, 'username')]

    • starts-with(): Locates elements with attribute values that begin with a defined keyword.

    //button[starts-with(@name, 'submit')]

    • text(): Finds elements based on visible text, useful for buttons and labels.

    //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.

    • Example with and:

    //input[@type='text' and contains(@placeholder, 'email')]

    • Example with or:

    //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.

    • Example using following-sibling:

    //label[text()='Password']/following-sibling::input

    • Example using ancestor:

    //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 Performance in Selenium

    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:

    • Prefer relative XPath: Use relative paths that begin with // instead of absolute ones that start from the root. Relative XPath adapts better to structural changes and executes faster.
    • Avoid wildcards and redundant axes: Refrain from using //* or unnecessary traversal axes. These cause Selenium to search the entire DOM, which reduces efficiency. Target specific element types or stable attributes instead.
    • Use stable and unique attributes: Rely on attributes that rarely change, such as data-test, aria-label, or a fixed class name. These are more reliable than dynamic IDs or autogenerated names.
    • Limit the number of conditions: Keep expressions concise by combining only the most relevant attributes. Too many conditions increase evaluation time and make XPath harder to maintain.
    • Validate XPath before implementation: Always test expressions in the browser console to ensure they return a single, correct match. Verifying them early prevents flaky tests later.
    • Cache frequently accessed elements: When an element is used repeatedly in a test, store its reference instead of re-locating it multiple times. This reduces repetitive XPath evaluations.

    Best Practices for Writing Robust Dynamic XPath

    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:

    • Prioritize clarity over complexity: Write XPath expressions that are easy to understand and maintain. Avoid chaining too many conditions or using complex hierarchies unless necessary.
    • Leverage meaningful attributes: Use semantic attributes such as aria-label, data-test, or title rather than auto-generated IDs or index-based locators. These are less likely to change with UI updates.
    • Combine conditions thoughtfully: Use logical operators like and or or to create precise locators without overcomplicating the expression. Balanced conditions ensure both flexibility and accuracy.
    • Include visible text when stable: When button labels, links, or headings remain constant, text-based locators can increase readability and reliability. However, avoid using text when the language or content changes dynamically.
    • Keep expressions adaptable: Combine functions such as contains() and starts-with() to handle partial matches for dynamic attributes. This approach makes XPath resilient against minor value changes.
    • Avoid dependency on DOM depth: Avoid using absolute indexing like [3] or long nested paths. Small UI changes can break such locators and increase script maintenance.
    • Review and refactor periodically: As applications evolve, regularly validate and refine XPath expressions to align with new UI elements or updated naming conventions.

    Handling Dynamic Web Elements in Selenium

    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: 

    • Use explicit waits for synchronization: Dynamic elements may take time to load or update. Apply explicit waits such as WebDriverWait with conditions like presenceOfElementLocated or elementToBeClickable to ensure Selenium interacts only when the element is ready.
    • Detect attribute or text changes: Some elements reload with updated IDs, text, or classes. Monitor such changes using functions like contains() or starts-with() in XPath to maintain flexible matching.
    • Handle dynamic frames or pop-ups: If the element is inside a frame or modal that loads dynamically, switch context using driver.switchTo().frame() or handle modal transitions before interacting with the element.
    • Re-locate elements after DOM updates: When the DOM refreshes or re-renders after a user action, previous element references may become stale. Re-fetch the element using the same dynamic XPath before performing the next operation.
    • Use conditional checks for optional elements: Some dynamic elements may appear only under specific conditions. Verify their presence with findElements() instead of findElement() to prevent exceptions when the element is missing.

    Testing Dynamic XPath on Real Devices

    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.

    Conclusion

    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

    Data-rich bug reports loved by everyone

    Get visual proof, steps to reproduce and technical logs with one click

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    “Game changer”

    Julie, Head of QA

    star-ratingstar-ratingstar-ratingstar-ratingstar-rating

    Overall rating: 4.7/5

    Try Bird later, from your desktop