Selenium · Browser automation foundations

When should you use XPath in Selenium?

Mediumxpathlocatorsdom traversalUpdated Oct 2026
Quiz this track

Short answer

Use XPath when you need text matching, parent or sibling traversal, or conditions CSS cannot express. Prefer relative paths with stable attributes over absolute paths tied to document structure.

XPath navigates the XML view of the DOM. It can match text, walk axes and combine conditions. That power makes it easy to write selectors that are clever but fragile, especially absolute paths copied from browser dev tools.

java
By byText = By.xpath("//button[normalize-space()='Save']");
By byContains = By.xpath("//button[contains(@class, 'primary')]");
By bySibling = By.xpath("//label[text()='Email']/following-sibling::input");
By byAncestor = By.xpath("//span[text()='Total']/ancestor::section");
By relative = By.xpath(".//input[@name='email']");
Relative paths start from the current context and are less coupled than absolute paths.
  • text() and normalize-space() match visible text with whitespace control
  • contains() handles partial attribute or text values
  • following-sibling and ancestor express relationships CSS cannot
  • A leading // searches from the document root; .// searches from the current node
  • Absolute paths such as /html/body/div[2]/form break on unrelated layout changes
  • XPath 1.0 is what browsers expose, so newer XPath functions are unavailable

Text-based XPath is convenient but couples tests to copy language and localisation. For user-visible text that is part of the specification, that coupling can be acceptable. For structural targets, an attribute is usually better.

Do not paste absolute XPath from dev tools into a suite. It records the current DOM, not the behaviour you care about.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between // and .//?
  2. 2Why is absolute XPath fragile?
  3. 3When is text-based XPath acceptable?
  4. 4Which XPath axes have you used in tests?

Say it in the interview

I reach for XPath when CSS cannot express the target, such as matching text or walking to a parent or sibling. I write relative paths with stable attributes and normalise whitespace for text. I avoid absolute paths from dev tools because they encode the current layout. If I am matching visible copy, I make sure that copy is part of the product contract and not a translation detail.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.