Contents

    Guides

    XPath in Selenium: What, Why, and How to Use It

    Published on

    September 11, 2025
    XPath in Selenium: What, Why, and How to Use It

    To ensure a smooth end user experience, testers need to fetch and validate the usability of web elements.

    XPath is a locator that enables your test scripts to interact with the underlying DOM tree to validate the functionality of your UI elements. You can navigate HTML or XML markdowns, find out elements to test by ID, hierarchy, or attributes, and test their functionality.

    This guide talks about absolute and relative XPath, chained XPath, common functions, handling dynamic elements, best practices, and examples.

    Run Selenium Tests on Cloud

    What is XPath in Selenium?

    XPath in Selenium is a query language used to locate elements in HTML or XML documents. It allows testers to target elements based on tag names, attributes, text content, or hierarchical relationships in DOM.

    XPath functionality can be absolute or relative. Absolute XPath defines the entire path from the app's project root to your test script but changes if the element ID or DOM has changed. 

    Relative XPath starts from a known reference point in the app's backend that you can retrieve from your test script using functions, conditions, or attributes and doesn’t impact any mainframe UI changes. 

    In Selenium, you cannot identify an element by describing it as a “blue button in the middle” or “the button above the form.” Instead, you use locators to identify the element through its HTML attributes, structure, or other properties in the DOM.

    Example of XPath

    An XPath can identify an element using its tag name, attributes, ARIA attributes, text content, position in the DOM, parent-child relationship, or sibling relationship.

    For example, consider this HTML:

    <button type="submit">Login</button>

    An XPath can locate the button using its attribute:

    //button[@type='submit'] 

    In Selenium Java, the expression can be used as follows:

    WebElement loginButton = driver. findElement(
        By.xpath("//button[@type='submit']")
    );
    
    loginButton.click();

    Here, the XPath identifies the <button> element with type="submit." Selenium then returns the matching element so the test can interact with it.

    XPath is particularly useful when a dynamic element, like a button, menu, or field, doesn’t have a unique ID, name, or class name. Instead of depending on a single attribute, testers can locate the element’s text, position, or relationship with other DOM elements.

    In other words, XPath translates the characteristics and structure of the underlying DOM into a locator that Selenium can use to find the exact element required by the test.

    The Role of XPath in Locating Web Elements

    XPath in Selenium identifies elements that cannot be reliably located with simpler locators such as ID, name, or class. It allows testers to navigate the DOM hierarchy and define precise conditions to select elements, which is especially important for complex web pages with dynamic content.

    Using XPath, testers can:

    • Target nested elements: Locate elements deep within a hierarchy where CSS selectors may not suffice. For example, selecting a button inside multiple div layers can be done using a single XPath expression.
    • Handle dynamic attributes: Identify elements based on partial matches of attributes using functions like contains() or starts-with(). This is useful when IDs or class names change dynamically.
    • Navigate relationships: Traverse parent, child, sibling, and ancestor nodes to locate elements relative to others, making tests more resilient to DOM changes.
    • Combine multiple conditions: Create expressions that match elements based on multiple attributes or text content, improving precision in identifying the correct target.

    Absolute and Relative XPath Explained

    While using XPath, you can choose either “absolute XPath” to target the whole path of a UI element or “relative XPath” to locate a unique ID.

    Say, if you are testing a login window, you can navigate the entire path consisting of the login button, call to DOM, and output. 

    A relative XPath identifies the target using relevant attributes, conditions, text, or relationships within the DOM.

    1. Absolute XPath

    Absolute XPath specifies every node in the hierarchy from the root <html> element to the target element.

    For example, consider a login form with a username input field:

    /html/body/div[2]/div/form/input[1] 

    This XPath instructs Selenium to navigate through each level of the DOM until it reaches the first <input> element inside the specified <form>.

    Because the expression depends on the exact structure of the page, it can precisely identify an element in a static DOM. However, it is also fragile.

    For example, if a developer adds another wrapper <div> around the login form, the DOM structure changes:

    The original XPath may no longer point to the correct element, even though the username field itself has not changed.

    This is why absolute XPath is generally less suitable for Selenium test suites that run against applications with frequently changing UI structures. A small structural update can require multiple locators to be updated, increasing test maintenance.

    2. Relative XPath

    Relative XPath starts from a relevant point in the DOM rather than defining the complete path from the root element.

    For the same username input field, a relative XPath could be

    //input[@id='username']

    This expression searches for an <input> element with the attribute id="username."

    XPath can also combine structural context with conditions:

    //form[@id='loginForm']//input[contains(@name,'user')] 

    Here, Selenium first identifies the form with the ID loginForm and then searches for an input within that form whose name attribute contains user.

    Unlike an absolute XPath, these expressions do not depend on every parent element between the root of the DOM and the target. As a result, adding containers or other elements elsewhere on the page is less likely to break the locator.

    Relative XPath can also combine multiple conditions when one attribute is not sufficient to identify an element.

    For example:

     //input[@type='text' and @name='username'] 

    This locator ensures that Selenium finds an input that matches both conditions.

    In most Selenium tests, relative XPath is preferred because it provides a better balance between precision and maintainability. However, a relative XPath should still be specific enough to uniquely identify the intended element. A shorter locator is not necessarily better if it matches multiple elements on the page.

    The general approach is to use the simplest stable XPath that identifies the correct element without unnecessarily depending on the complete DOM hierarchy.

    Chained XPath in Selenium

    Chained XPath in Selenium refers to combining multiple XPath expressions to locate elements in a step-by-step manner. This is useful when an element cannot be uniquely identified by a single attribute or when it is nested inside multiple parent elements. Chaining allows testers to navigate through the DOM progressively to reach the target element.

    For example, consider a table where you want to click a button in a specific row based on the row’s text:

    //table[@id='userTable']//tr[td[text()='John Doe']]//button[text()='Edit']

    Here, the XPath first locates the table, then the row containing "John Doe," and finally the "Edit" button within that row. This reduces ambiguity and increases accuracy when multiple similar elements exist on the page.

    Chained XPath is particularly effective in scenarios such as:

    • Tables with multiple rows: Selecting a button, link, or input field in a specific row.
    • Nested elements: Locating elements inside multiple containers or divs.
    • Dynamic lists or grids: Selecting elements based on text or attributes when IDs or classes are not unique

    Situations Where Chained XPath Works Best

    Chained XPath works when you cannot rely on a single method to locate an element. It identifies an element not via element’s unique attributes, but it’s position within a larger structure. 

    1. Repeated components with no unique identifiers: 

    Product cards, list items, menus, tables, and search results are often executed with the same XML sitemap. They can be used to locate buttons, labels or inputs that fall under it, as those elements might share identical classes. 

    Chaining lets you locate a similar class or attribute before locating the actual element inside it.

    2. Elements inside a specific row or card

    When a table or a list contains multiple rows with the same structure and data type, Chained XPath can isolate other elements to locate the element relative to it.

    //tr[td[text()='Invoice #1042']]//button[@class='delete-btn']

    This finds the row containing Invoice #1042 and then locates the delete button within that specific row, rather than the first delete button on the page.

    You can also use Following-Sibling XPath in Selenium for this.

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

    This says, "Find the label with the text 'Username,' then find the input that comes after it and shares the same parent."

    3. Nested UI components (modals, dropdowns, accordions)

    Modals and dropdowns often use the same internal structure as other components of a single page app. Chaining from the dropdown ensures the element is rendered in a visible way, rather than locating it from scratch. 

    4. Multi-step forms or grouped fields

    When a form is broken into sections (billing vs. shipping address, for example), fields in each section may share the same name or type attributes. Chaining from the section heading or fieldset narrows the locator to the correct group:

     //fieldset[legend[text()='Shipping Address']]//input[@name='zip']

    Chained paths should follow the right method: define the locator first (lazy evaluation), and only run the script once the element is rendered and visible in the DOM.

    Locating Login Page Elements Using XPath: Step-by-Step Example

    To demonstrate XPath in Selenium, consider a login page with username, password fields, and a login button. This example shows how to locate elements even when IDs or classes are missing or dynamically generated.

    Step 1: Locate the username input using relative XPath:

    //input[@name='username']

    Step 2: Locate the password input using attribute-based XPath:

    //input[@name='password'] 

    Step 3: Locate the login button using text-based XPath:

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

    If multiple login buttons exist on the page, chained XPath ensures the correct element is selected:

    //form[@id='loginForm']//button[text()='Login']

    This step-by-step approach demonstrates how XPath can target elements accurately, handle dynamic content, and reduce test flakiness. Functions like contains() or starts-with() can further enhance locator stability in real-world scenarios.

    Common XPath Functions in Selenium

    Not every element can be located using an exact attribute value or an exact text match. Dynamic applications may generate changing IDs, append values to class names, or display elements whose text varies slightly between states.

    XPath functions help testers create more flexible locators in these situations.

    The most commonly used XPath functions in Selenium include contains(), starts-with(), and text().

    1. contains()

    The contains() function allows testers to locate elements based on a partial match within an attribute or text value.

    For example:

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

    This matches an input element whose id contains the value user.

    It can be useful when part of an attribute is stable while another part is generated dynamically. For example, an application might generate IDs such as

    user_12345
    user_84721
    user_profile_678 
    

    An exact locator based on the complete ID may break when the dynamic value changes. A partial match can instead rely on the stable portion of the attribute.

    contains() can also be used with text:

     //button[contains(text(),'Continue')]

    However, partial matching should be used carefully. If several elements contain the same text or attribute value, the XPath may match more than one element. Adding another condition or narrowing the locator to a stable parent can improve precision.

    2. starts-with()

    The starts-with() function identifies elements whose attribute values begin with a specified string.

    For example:

    //button[starts-with(@id,'btnLogin')] 

    This matches buttons with IDs that start with btnLogin, regardless of the suffix.

    For example:

    btnLogin_1
    btnLogin_847
    btnLogin_primary
    

    This is useful when an application maintains a consistent attribute prefix while generating the remaining value dynamically.

    As with contains(), the stable portion used in the locator should be specific enough to avoid matching unintended elements.

    3. text()

    The text() function allows XPath to locate an element based on its text content rather than an attribute.

    For example:

    //a[text()='Forgot Password?'] 

    This selects a link whose exact text is Forgot Password?.

    Text-based XPath can be useful for:

    • Buttons
    • Links
    • Labels
    • Menu items
    • Headings

    where a stable identifying attribute is unavailable.

    However, exact text matching can become fragile when UI copy changes or the application supports multiple languages.

    When extra whitespace is present in the DOM, normalize-space() can be useful:

    //button[normalize-space()='Login']

    This makes the locator less sensitive to unnecessary whitespace around the text.

    Used appropriately, these functions allow XPath expressions to adapt to dynamic attributes and content while retaining enough specificity to locate the correct element.

    What are XPath Axes?

    XPath Axes in Selenium define relationships between nodes in the DOM, allowing testers to navigate relative to a known element. Axes make it possible to select parents, children, siblings, or ancestors, which is especially useful for complex or nested web page structures.

    For example, the parent axis can locate an element’s parent node:

    //input[@id='username']/parent::div

    This selects the div containing the input field, enabling actions on the container rather than the element itself.

    The following-sibling axis allows selecting elements that appear after a reference element on the same hierarchy level:

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

    This locates the input field that immediately follows the “Password” label, which is helpful when multiple input fields have similar attributes.

    Other commonly used axes include ancestor, preceding-sibling, child, and descendant. Using axes strategically can reduce reliance on fragile absolute paths and improve the reliability of Selenium tests on dynamic pages.

    Creating Stable XPath for Dynamic Elements

    Dynamic web applications can change the DOM without changing the intended user workflow.

    For example, if an end user is trying to check out, the checkout button may be changed in position later in the flow and might now have a different ID. Or there might be more than one “checkout button."

    XPath locators that depend only on IDs that change between sessions can therefore cause Selenium tests to fail.

    Creating stable XPath expressions requires identifying which characteristics of an element are likely to remain consistent as the UI changes.

    1. Use Partial Matches for Dynamic Attributes

    When an attribute contains both stable and dynamic values, contains() or starts-with() can help.

    For example:

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

    This identifies an input using the stable portion of its ID rather than depending on a dynamically generated suffix.

    Similarly:

     //button[starts-with(@id,'btnLogin')]

    can locate a button with a predictable ID prefix.

    Partial matching should still be specific enough to avoid matching multiple elements

    2. Use Stable Parent Context

    Another approach is to locate an element relative to a stable parent.

    For example:

    //form[@id='loginForm']//input[@type='password']

    The password field is located within the specific login form rather than globally across the page.

    This reduces the risk of selecting another matching password field and makes the XPath less dependent on the complete DOM hierarchy.

    Stable parent context can include forms, tables, cards, dialogs, sections, and application components with stable attributes.

    3. Use Text or DOM Relationships

    When attributes are dynamic but the surrounding structure remains stable, text and relationships can provide useful alternatives.

    For example:

    //button[normalize-space()='Submit'] 

    uses the button's text.

    Similarly:

    //label[normalize-space()='Email']/following-sibling::input 

    uses the relationship between the label and its associated input.

    The locator does not depend on the input having a unique ID. Instead, it uses stable context within the DOM.

    4. Combine Multiple Conditions

    If one condition is too broad, XPath can combine conditions.

    For example:

    //input[@type='email' and contains(@name,'user')] 

    This locator matches an input only when both conditions are true.

    Combining stable conditions can improve locator precision without requiring a long and fragile absolute XPath.

    5. Distinguish Dynamic Locators From Dynamic Loading

    A correct XPath can still fail if the target element has not yet appeared in the DOM or is not ready for interaction.

    For example, a button may load asynchronously after an API request. Changing the XPath will not solve this issue if Selenium attempts to interact with the button before it becomes clickable.

    In this situation, synchronization is required:

    WebDriverWait wait = new WebDriverWait(
        driver,
        Duration.ofSeconds(10)
    );
    
    WebElement loginButton = wait. until
        ExpectedConditions.elementToBeClickable(
            By.xpath("//button[@type='submit']")
        )
    );
    
    loginButton.click();
    

    Here, XPath determines which element Selenium should locate, while the explicit wait determines when Selenium should interact with it.

    Separating locator stability from synchronization issues can make XPath failures easier to debug and reduce flaky Selenium tests.

    The key is to manage asynchronous rendering in dynamic web pages with XPath so you can fetch the right UI details and validate them.

    XPath vs. CSS Selectors in Selenium

    XPath and CSS selectors are both widely used locator strategies in Selenium. Neither is automatically the best option in every situation.

    The choice depends on how the target element can be most clearly and reliably identified.

    Factor XPath CSS Selector
    Attribute matching Supported Supported
    Text matching Supported Not directly supported by standard CSS selectors
    Parent and ancestor navigation Supported Cannot directly select a parent based on a child
    Sibling navigation Supported through axes Supported for certain sibling relationships
    Complex DOM relationships Highly flexible More limited
    Readability for simple locators Can become verbose Often shorter
    Browser support Supported by Selenium WebDriver Supported by Selenium WebDriver

    For a straightforward attribute-based element, a CSS selector can be concise:

    input[name='username']

    The equivalent XPath is

    //input[@name='username']

    Both locators can identify the same element.

    XPath becomes particularly useful when locating an element through text or a relationship with another element:

    //label[normalize-space()='Email']/following-sibling::input

    The best approach is to choose the simplest stable locator that uniquely identifies the required element.

    Best Practices for Writing XPath in Selenium Tests

    Writing effective XPath in Selenium requires balancing precision and resilience. Well-constructed XPath locators reduce test flakiness, simplify maintenance, and improve the overall reliability of automation scripts.

    • Prefer relative XPath over absolute: Absolute paths break easily with minor DOM changes. Using relative XPath with stable reference points improves maintainability.
    • Use attributes strategically: Target elements using unique or consistent attributes like id, name, or type. When attributes are dynamic, combine them with functions like contains() or starts-with().
    • Leverage text when appropriate: For buttons, links, or labels with static text, using text() ensures the correct element is selected even when attributes change.
    • Avoid overly complex chains: Excessive nesting or combining many conditions can make XPath hard to read and maintain. Keep expressions simple while still precise.
    • Test XPath expressions in the browser: Validate locators using browser developer tools before adding them to Selenium scripts. This ensures accuracy and reduces debugging time

    Using Real Device Labs for XPath Validation

    Real device labs provides a cloud-based platform to run Selenium tests across real browsers and devices. It helps testers validate XPath locators in different environments without setting up local infrastructure, ensuring consistent behavior across browsers.

    With BrowserStack, testers can:

    • Execute cross-browser tests: Run Selenium scripts with XPath locators on multiple browser versions simultaneously to catch inconsistencies.
    • Test on real devices: Validate locators on actual mobile and desktop devices, ensuring dynamic or nested elements render correctly.
    • Debug failed locators: Use screenshots, video recordings, and logs to quickly identify which XPath expressions fail and why.
    • Integrate with CI/CD pipelines: Automatically test XPath locators during development, reducing regressions caused by DOM changes.

    Conclusion

    XPath can create direct linkages with underlying UI elements so that you can test and validate them.

    Understanding absolute and relative paths and how to handle dynamic elements with XPath can allow for smooth inter-device testing and cross-browser compatibility.

    XPath should also be selected as part of a broader locator strategy. CSS selectors may be simpler for straightforward attribute-based elements, while XPath can provide more flexibility when text matching or DOM relationships are required.

    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