How to use XPath in Selenium in 2026?

Related Product On This Page What is XPath in Selenium?

April 09, 2026 · 16 min read · Tool Comparison
Related Product

How to use XPath in Selenium in 2026?

Many testers assumeXPath in should be debar unless there ’ s absolutely no other choice. IDs feel safer, seem simpler, and XPath oftentimes gets labeled as slow or fragile.

I believed that too—until astarted failing after a minor UI update. The application still worked, but the DOM structure had vary just enough tobreak respective locater.

I seek switching selectors, adding postponement, and rebroadcast tryout repeatedly, but nothing brought lasting stableness. Hours went into, only to agnise the fixes be as brittle as the original ones.

That ’ s when it get clear the issue wasn ’ t XPath itself, but a lack of understanding of how to use it properly.

Overview

XPath in Selenium is a powerful locator strategy used to navigate through the HTML DOM and identify web elements when common locators like ID or name are not honest or available.

Basic XPath Syntax

XPath expressions use path patterns such as //tagname [@ attribute= & # 8217; value & # 8217;] to locate elements based on their structure, attributes, or visible textbook.

Types of XPath

  • Absolute XPath:Starts from the root of the DOM and follows the complete path to the ingredient.
  • Relative XPath:Starts from any node in the DOM and is more flexible and commonly used in Selenium mechanisation.

Key XPath Functions and Techniques

  • Functions like contains (), starts-with (), and text () help handle dynamic attribute.
  • XPath axes enable navigation through parent, child, sib, and ancestor relationships in complex DOM structures.

This article search how to use XPath in Selenium effectively, covering essential concept and practical techniques to establish more stable and maintainable test mechanisation.

What is XPath in Selenium?

XPath (XML Path Language) is alocater schemehabituate in Seleniumto identify and interact with web elementsby sail through the HTML structure.

It allows testers tolocate elementsbased on theirtag names, attributes, text values, and relationships with other elements, create it especially useful when common locators like ID or name are not available or are dynamically generated.

According toCrissy Joshua, a package testing expert, when using XPath in Selenium favorrelative and stable XPath expression over long, downright paths, as they are less likely to break with minor UI or DOM changes.

This coming ameliorate locator reliability, reduce test care effort, and results in more resilient automation scripts.

In declamatory test suites, validating XPath reliability across different browsers and environs becomes equally important.

Platforms like assistant squad run Selenium tests on existent browser and devices, do it easier to verify that XPath locators deport systematically across vary without maintaining local infrastructure.

Struggling with flaky Selenium test?

Dynamic DOM changes can break XPath locators. Test on real browser–OS combination to catch issues.

Types of XPath in Selenium

Here is a quick overview of the two types of Selenium XPath:

  • Absolute XPath: Begins from the root of the HTML papers and specifies the complete path to the element. It & # 8217; s not as pliable and can break if the page structure changes.
  • Relative XPath: Starts from a specific element and navigates through the DOM hierarchy to locate the desired element. It & # 8217; s more flexible and bouncy to changes in the page construction.

1. Absolute Path

The bare XPath locater example in Selenium is to provide the absolute path of an element in the DOM structure.

For case, consider the HTML below:

& lt; html & gt; & lt; nous & gt; ... & lt; /head & gt; & lt; body & gt; ... & lt; shape & gt; & lt; input name= '' name '' type= '' text '' value= '' First Name '' / & gt; & lt; input name= '' name '' type= '' text '' value= '' Last Name '' / & gt; & lt; input name= '' e-mail '' type= '' schoolbook '' value= '' Business Email '' / & gt; & lt; input name= '' password '' type= '' password '' / & gt; & lt; input name= '' continue '' type= '' submit '' value= '' Sign Me Up '' / & gt; & lt; /form & gt; & lt; /body & gt; & lt; /html & gt;

The syntax to choose the business email field is as follow:

html/body/form/input [3]

This searches for the maiden pattern tag in the body of the page and selects the third input battlefield in the form. This formatting, though simple, is also the most vulnerable to minor changes in the page & # 8217; s structure. This method is also cognize as a single slash search.

Read More: 

2. Relative Path

A comparative way, or a double slash search, get with double virgule. The three-fold slashes intend a break in the absolute itinerary. Here is how to select the same job email battlefield using a relative path.

//form/input [3]

If multiple forms exist on the page, one may need to provide an extra identifier for the form field.

Talk to an Expert

What is Chained XPath in Selenium?

A chained XPath in Selenium is the practice of combining legion XPath queries to locate an element on a web page in a more exact and decipherable manner. Instead of make a individual, complex XPath, you fraction it into smaller, more manageable chunks and connect them together with functions like findElement or findElements.

When to Use Chained XPath?

Chained XPath is especially good for complicated web pages when items are embedded behind multiple levels of HTML tags and you require to keep your tryout scripts open and flexile.

Advantages of apply Chained Xpath

  • Readability:Dividing the XPath into smaller sections can make it easier to read and comprehend.
  • Reusability:Intermediate elements, such as container, can be used to locate other child component in the same telescope.
  • Flexibility:Chaining enables you to interact with elements step by pace, which is useful when work with dynamic info.

Example of Chained XPath and Explanation

Assume you wish to locate a specific input battlefield inside a form with a afford id.

Single Complex XPath would be:

//form [@ id='loginForm '] //input [@ name='username ']

This manifestation locates the input field by fix the whole path in a single XPath twine.

Chained XPath would be:

WebElement form = driver.findElement (By.xpath (`` //form [@ id='loginForm '] '')); WebElement usernameInput = form.findElement (By.xpath (`` .//input [@ name='username '] ''));

This method first locates the kind element with the id loginForm. Then, within that form, it finds an input field with the name dimension set to username.

The advantages of using chained XPath to locate an & # 8216; input & # 8217; battleground within a & # 8216; kind & # 8217; are as follows:

  1. Improved Readability:Breaking down the XPath into smaller part make the code easier to say and comprehend. By first situate the & # 8216; form & # 8217; element and then the & # 8216; input & # 8217; within it, the code becomes more intuitive and error-free.
  2. Increased Maintainability:The average & # 8216; sort & # 8217; element can be apply to locate farther elements within the same & # 8216; shape & # 8217;. This modular approach simplifies cipher updates and maintenance because modification to the structure of the & # 8216; form & # 8217; element do not require modifications to the total XPath enquiry.
  3. Simplified Debugging:Isolating the steps allows you to more easily detect and troubleshoot mistake. If the & # 8216; input & # 8217; battleground is not discovered, you can get by see that the & # 8216; variety & # 8217; element is correctly place, which will make troubleshooting easier.
  4. Effectiveness through Targeted Searches:Chained XPath restricts the hunt to a specific section of the Document Object Model (DOM). This can do element location more efficient by lowering the amount of elements Selenium must look for.
  5. Flexibility: Dynamic Content:In active web applications with changing content, chained XPath is useful for cover for components that may be loaded or modified at runtime. It permit you to focalise on a specific area of the page, create it easier to manage dynamic info within a predefined container.

Overall, chaining XPath expressions improves code legibility and maintainability, particularly in complicated HTML structures.

XPath Locators

XPath (XML Path Language) locator in Selenium WebDriver are a potent tool for locating elements within an XML document or HTML page. XPath reflection use the document & # 8217; s construction to locate component based on attribute, tag names, or hierarchical relationships.

Some Key Features of XPath Locators are:

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

1. Versatility:It can either be Absolute (Specifies the route from the root to the target factor. For example,//html/body/div/p.) or Relative (Starts at a specified node and employ conditions to find elements.
For model://div [@ id= & # 8217; container & # 8217;] .//p [@ class= & # 8217; text & # 8217;].)

2 Flexible Element Selection:

  • By Tag Name: Selects elements establish on their tag names, such as //input, which selects all input component.
  • By Attribute: Locates items establish on their attribute.
  • For exemplar, //input [@ name= & # 8217; username & # 8217;] selects an stimulation element with the gens attribute set to & # 8216; username & # 8217;.
  • By Text Content: Finds point that incorporate sure textbook, such as //button [text () = & # 8217; Submit & # 8217;] picks a button labeled & # 8216; Submit & # 8217;.
  • By Hierarchical locating: Selects component agree to their location in the document hierarchy; for example, //div [1] choose the initiative div component.

3. Axes:Leverages Axes to scan the web page

  • Parent:choose the parent node; for example,‘..’take the current node & # 8217; s parent.
  • Child:Selects child nodes; for example,//div/child:: *selects all of div & # 8217; s child elements.
  • Sibling:Selects sibling knob, such as//div/following-sibling:: *, which selects all of div & # 8217; s siblings.

4. Predicates:These are Condition-Based and Filters elements based on conditions, such as//input [@ type= & # 8217; text & # 8217;]. [1]take the first text-based comment element.

5. Functions:Leverages functions like:

  • Contains ()returns elements with partial match, such as//div [contains (@ class, & # 8216; header & # 8217;)].
  • Starts-With ():Matches elements whose attributes begin with a certain value, such as//input [starts-with (@ id, & # 8216; user & # 8217;)].

Some illustration are :

Locate a Button by Text:

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

Find an Input Field by ID:

//input [@ id='username ']

Advantages and Disadvantages of XPath Locators

XPath locator are widely used in Selenium for their flexibility and preciseness in element designation. Understanding their strengths and limitations helps quizzer decide when XPath is the right alternative and how to use it effectively.

Advantages of XPath Locators:

  1. XPath is powerful and flexible, allowing for complicated lookup to precisely place detail based on a variety of parameters.
  2. Because XPath can adapt to changes in page structure, it is particularly beneficial for pages with dynamic content.

Disadvantages of XPath Locators:

  1. Complex XPath queries may be slower than simpler locators such as CSS selectors.
  2. XPath verbalism that rely on specific structures or attributes may fail if the page structure changes.

Read More:

Xpath Axes

XPath axes are a crucial component in XPath that permit you to travel through the nodes of an XML or HTML document in different directions relative to the context node. Each axis make a distinct relationship between nodes, make it easier to prefer detail depending on their place and relationship within the document hierarchy.

Some XPath Axes are:

  1. Ancestor:Selects the current node & # 8217; s ascendent nodes (except the node itself). E.g //p/ancestor: :div selects all div elements that are ancestors of p.
  2. Ancestor-or-self:Selects all ancestors of the current node, including the node itself. Example://p/ancestor-or-self: :divselects the div element itself and all its ancestor div component.
  3. Attribute:Selects attribute of the current node.//input/attribute: :typeselect the character attribute of stimulation component.
  4. Child:Selects all child thickening of the current node. Example://div/child::* choose all child elements of div
  5. Descendant:Selects all descendant thickening (children, grandchildren, etc.) of the current node. Example,//div/descendant-or-self: :spanselects the span elements inside div, as well as div itself if it is a span.
  6. Following:Selects all thickening that get after the current node in the document, shut any descendants. Example.//h2/following: :pselects allpconstituent that postdate anh2 element.
  7. Following-sibling:Selects all siblings that come after the current node.//h2/following-sibling: :pselects allpelements that are siblings following anh2.
  8. Namespace:Selects namespace node of the current node. Example,//element/namespace::* selects all namespace nodes for the element.
  9. Parent:Selects the parent node of the current node.//p/parent: :divselects the div parent of ap element.
  10. Preceding:Selects all nodes that semen before the current node in the document, excluding any ancestors. Example.//p/preceding: :h2selects allh2element that forgop.
  11. Preceding-sibling:Selects all siblings that come before the current node.//p/preceding-sibling: :h2selects allh2elements that are siblings precedingp.
  12. Self:Selects the current node itself.//div/self: :divselects the div ingredient itself.

When to use XPath Axes

  1. XPath axe are useful for browsing and choosing nodes based on their relationship to other nodes, making it easier to entree point in a given context.
  2. They enable more complex inquiry that uncomplicated locator may not be capable to handle, such as picking items based on their relative position to former nodes.

Some Examples with Chained XPath

Suppose you feature the following HTML structure and you want to site a specific input battleground based on its relationship with other component:

& lt; div & gt; & lt; form & gt; & lt; fieldset & gt; & lt; legend & gt; Login & lt; /legend & gt; & lt; div & gt; & lt; label for= '' username '' & gt; Username: & lt; /label & gt; & lt; input type= '' text '' / & gt; & lt; /div & gt; & lt; div & gt; & lt; label for= '' word '' & gt; Password: & lt; /label & gt; & lt; input type= '' password '' / & gt; & lt; /div & gt; & lt; /fieldset & gt; & lt; button type= '' submit '' & gt; Submit & lt; /button & gt; & lt; /form & gt; & lt; /div & gt;

1. You can find the input Field Based on Its Label

You can find the input field for & # 8220;username& # 8221; by 1st locating the label and then the corresponding input battlefield, you can use XPath ax in a chained manner:

// Locate the ` label ` element WebElement label = driver.findElement (By.xpath (`` //label [text () ='Username: '] ''));
// Use the ` ancestor ` axis to find the closest ancestor ` div ` with the class ` form-group ` WebElement formGroup = label.findElement (By.xpath (`` ./ancestor: :div [@ class='form-group '] ''));
// Use the ` following-sibling ` axis to locate the ` remark ` battleground within the same ` form-group ` WebElement usernameInput = formGroup.findElement (By.xpath (`` ./input [@ id='username '] ''));

2. Finding the input Field by Using a Combination of ancestor and descendant Axes

If you need to regain the input field directly by navigating through its ancestor form and then finding it within the fieldset, you can use:

// Locate the ` pattern ` element WebElement pattern = driver.findElement (By.xpath (`` //form [@ id='loginForm '] ''));
// Use the ` descendant ` axis to find the ` input ` field within the form WebElement usernameInput = form.findElement (By.xpath (`` .//input [@ id='username '] ''));

Explanation

  • Ancestor Axis:This axis help in navigating up the DOM tree to site ancestor elements of the current node. In the first representative, we use the ancestor axis to find the closest div with a specific class.
  • Following-Sibling Axis:This axis allows pilot to sibling elements that postdate the current node. It & # 8217; s useful when the factor you need is a sibling of another cognize element.
  • Descendant Axis:This axis is used to select all descendent thickening of the current node. In the 2d representative, it simplifies locating the input element within a specific form.
  • Chaining XPath expressionswith different axes allows you to precisely find components even in complicated and nested HTML structure, making your tests more reliable and maintainable.

How to handle Dynamic Elements in Selenium using XPath?

Dynamic elements can make Selenium tests precarious when attribute or DOM structures change frequently. Using XPath effectively helps create pliant locators that conform to these changes and keep exam reliable.

1. Using Attributes

While the example shown supra is feasible if simply a single form is on the page, one can make the lookup patterns more robust by using attributes.

//form [@ id='loginForm '] /input [3]

In place of id, one can use any attribute and its equate value to locate an element with Selenium.

While this representative shows a individual attribute, one can likewise use multiple attributes of the like tag to place it on the page.

For instance, to take the Terminal Name battlefield, one can use the following XPath syntax in Selenium:

//input [@ name='name '] [@ value='Last Name ']

2. Logical Operators in Selections

While attributes may be sufficient to locate elements in most cases, testers may also need to use logical operators.

For instance, if the HTML construction has name or id attributes populated by the value “ name ”, one may use the following syntax to select them.

//input [@ id='name ' or @ name='name ']

Similarly, one can supercede theorkeyword withandto entirely choose an element that meet all weather.

Also Read:

3. Using Text

One may search for an element using the schoolbook that it contains too. For instance, to choose a link that says “ Click Me ”, one can use the next search:

//a [schoolbook () ='Click Me ']

This snippet searches for any hyperlink containing the schoolbook “ Click Me ”. Replace the tag with a wildcard*to look for any element that contains the schoolbook “ Click Me ”.

// * [schoolbook () ='Click Me ']

While these XPath techniques help brace locater in dynamic covering, validating them across different browser and surroundings is equally important.

As test suites scale, ensuring ordered behavior without increase maintenance overhead becomes a key challenge—this is where the correct test infrastructure can significantly amend efficiency.

Learn More:

How BrowserStack Automate do Selenium Testing efficient?

While well-written XPath locators ameliorate test stability, validating them systematically across browsers and environments is critical for reliable mechanisation.

BrowserStack Automate help teams move beyond local execution and scale Selenium try efficiently without added substructure complexity.

BrowserStack Automate improve Selenium testing efficiency by:

  • Running Selenium examination on 3500+ real browsers and devices, ensuring XPath locators behave consistently across real user environments
  • Supporting executionto significantly reduce overall tryout runtime
  • Allowing existing Selenium scripts to runwithout any codification changes, include XPath-based locater
  • Automatically capturingscreenshots, video recordings, console log, and network logsfor every test session
  • Providing centralized access to all debugging artifacts through the BrowserStack dashboard

By combining real-device try with built-in debugging and scalability, BrowserStack Automate enables quicker feedback, easier failure analysis, and more reliable Selenium automation.

Conclusion

XPath remains one of the most powerful locator strategies in Selenium when consider with complex, dynamical, or deeply nested web covering.

By understanding different XPath types, axes, and technique for deal dynamic elements, testers can progress more stable and maintainable automation scripts.

However, reliable locater alone are not enough. Validating XPath behavior across real browser and devices is essential to avoid flaky tests and unexpected failures in production.

By combining well-structured XPath strategies with scalable real-browser screen using BrowserStack Automate, teams can achieve faster feedback, potent test reliability, and more confident Selenium automation.

Tags

FAQs

XPath locater look on the DOM structure and attributes, so even pocket-sized UI or attribute changes can cause them to fail if they are not compose to be pliable.

Using proportional XPath, stable attributes, functions like contains () or starts-with (), and avoiding absolute paths helps reduce failure caused by dynamic DOM changes.

Different browser can interpret DOM provide and timing otherwise. Testing on existent browsers ensures XPath locators work systematically across actual user surround.

60,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free