Thursday, 1 October 2026

XPath in Selenium: Complete Tutorial with Examples

 

Introduction

XPath is one of the most important skills in Selenium automation testing. It helps automation testers identify web elements when simple locators such as ID, Name or Class Name are unavailable or unreliable.

Modern web applications frequently contain dynamic elements, complex page structures and repeated HTML attributes. In such situations, XPath provides flexible ways to locate buttons, text fields, links, dropdowns and other web elements.

In this tutorial, we will understand XPath syntax, different XPath techniques, practical Java examples and best practices for using XPath in Selenium WebDriver.

What Is XPath?

XPath stands for XML Path Language. It is used to navigate through elements and attributes in an XML or HTML document.

In Selenium, XPath helps identify elements on a webpage so that automated test scripts can interact with them.

Consider this HTML:

<input id="username" name="user" type="text">

The corresponding XPath expression is:

//input[@id='username']

Java implementation:

driver.findElement(
    By.xpath("//input[@id='username']")
).sendKeys("testuser");

1. Types of XPath in Selenium

There are two commonly discussed forms of XPath.

Absolute XPath

Absolute XPath starts from the root element and follows the complete hierarchy of the HTML document.

Example:

/html/body/div/form/input

Advantages:

  • Represents the complete document path.

  • Can identify elements through their hierarchy.

Disadvantages:

  • Highly dependent on page structure.

  • Can break when developers change the HTML layout.

  • Difficult to maintain in large automation projects.

Relative XPath

Relative XPath starts from anywhere in the document using //.

Example:

//input[@id='username']

Relative XPath is generally preferred because it allows testers to identify elements using attributes, text and relationships rather than depending on the entire page hierarchy.

2. XPath Using Attributes

Attributes are among the most commonly used ways to create XPath expressions.

HTML:

<input type="text" name="email" id="email">

XPath:

//input[@name='email']

Other examples:

//input[@id='email']
//input[@type='text']
//button[@class='submit-button']

Java example:

driver.findElement(
    By.xpath("//input[@name='email']")
).sendKeys("test@example.com");

3. XPath Using Text

XPath can locate elements using their visible text.

HTML:

<button>Submit</button>

XPath:

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

Java:

driver.findElement(
    By.xpath("//button[text()='Submit']")
).click();

For elements where text contains additional spaces or nested elements, normalize-space() can be useful:

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

4. XPath Using Contains()

The contains() function is useful when an attribute value is dynamic or only part of the value is predictable.

Example:

//button[contains(@class,'submit')]

Java:

driver.findElement(
    By.xpath("//button[contains(@class,'submit')]")
).click();

It can also be used with text:

//a[contains(text(),'Register')]

This technique is helpful when dealing with changing element names or partial text values.

5. XPath Using Starts-With()

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

Example:

//input[starts-with(@id,'user')]

Suppose the application generates IDs such as:

  • user_101

  • user_102

  • user_103

The above XPath can identify all these elements based on their common prefix.

6. XPath Using Multiple Attributes

Sometimes one attribute is not sufficient to identify an element uniquely. You can combine multiple conditions using logical operators.

Using AND:

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

Using OR:

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

Java example:

driver.findElement(
    By.xpath("//input[@type='text' and @name='username']")
).sendKeys("admin");

Use multiple attributes when they make the locator more specific and stable.

7. XPath Using Index and Position

When multiple elements have similar attributes, XPath can use position to identify a particular match.

Example:

(//input[@type='text'])[1]

To select the second matching element:

(//input[@type='text'])[2]

You can also use:

//table//tr[position()=2]

Remember that XPath positions are generally one-based. However, index-based locators can become unreliable when the page layout or element order changes.

8. Advanced XPath Axes

XPath axes help locate elements based on their relationships with other elements.

XPath AxisPurpose
parentSelects the parent element
childSelects direct child elements
ancestorSelects parent and higher-level ancestors
descendantSelects all descendants
following-siblingSelects later siblings
preceding-siblingSelects earlier siblings
followingSelects elements appearing later in document order
precedingSelects elements appearing earlier in document order

Parent Axis

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

Child Axis

//form/child::input

Following-Sibling Axis

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

Ancestor Axis

//input[@id='email']/ancestor::form

These techniques are especially useful when an element does not have a unique ID or Name attribute but has a predictable relationship with another element.

9. XPath Using normalize-space()

Web applications sometimes contain extra spaces or line breaks in visible text.

The normalize-space() function removes leading and trailing spaces and reduces consecutive whitespace.

Example:

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

This can improve locator reliability when the HTML contains inconsistent whitespace.

10. Practical XPath Example in Selenium Java

The following example demonstrates XPath-based interaction with a web application.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class XPathExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {
            driver.get("https://example.com");

            driver.findElement(
                By.xpath("//input[@id='username']")
            ).sendKeys("testuser");

            driver.findElement(
                By.xpath("//input[@name='password']")
            ).sendKeys("Test@123");

            driver.findElement(
                By.xpath("//button[normalize-space()='Login']")
            ).click();

        } finally {
            driver.quit();
        }
    }
}

The URL and XPath expressions are illustrative. Replace them with the actual application URL and HTML attributes used in your testing environment.

11. Common XPath Mistakes to Avoid

  1. Using absolute XPath for every element.

  2. Depending on dynamic IDs that frequently change.

  3. Creating unnecessarily long XPath expressions.

  4. Ignoring spaces and case differences in text.

  5. Using index-based XPath without checking element order.

  6. Failing to verify whether the XPath identifies the intended element.

  7. Using XPath when a stable ID or simpler CSS Selector is available.

Best practice: Prefer short, readable and stable XPath expressions. Validate them in browser developer tools before using them in automation scripts.

Frequently Asked Questions

1. What is XPath in Selenium?

XPath is a locator strategy used by Selenium WebDriver to identify elements in an HTML document.

2. Which XPath is better: absolute or relative?

Relative XPath is generally preferred because it is less dependent on the complete HTML hierarchy.

3. What is the difference between contains() and starts-with()?

contains() checks whether an attribute or text contains a particular string. starts-with() checks whether it begins with a specified string.

4. What are XPath axes?

XPath axes identify elements based on their relationships, such as parent, child, ancestor and sibling.

5. Can XPath locate elements using visible text?

Yes. Expressions such as //button[text()='Login'] can identify elements based on their text content.

6. Is XPath better than CSS Selector?

Neither is universally better. CSS Selectors are concise for many attribute-based searches, while XPath supports text matching and flexible navigation through document relationships.

Learn Selenium Automation Testing with Palium Skills

Develop practical automation testing skills with Palium Skills through structured training in Selenium and Playwright.

The training can cover:

  • Selenium WebDriver with Java and Python

  • XPath and CSS Selector techniques

  • TestNG and PyTest frameworks

  • Page Object Model and framework development

  • API testing and automation

  • Real-time practical projects

  • Interview preparation and career guidance

Training modes: Classroom training at South Kolkata and Salt Lake centres, and instructor-led live online training for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Visit Palium Skills to explore practical Selenium and Playwright automation testing courses.

No comments:

Post a Comment

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...