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/inputAdvantages:
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 Axis | Purpose |
|---|---|
parent | Selects the parent element |
child | Selects direct child elements |
ancestor | Selects parent and higher-level ancestors |
descendant | Selects all descendants |
following-sibling | Selects later siblings |
preceding-sibling | Selects earlier siblings |
following | Selects elements appearing later in document order |
preceding | Selects elements appearing earlier in document order |
Parent Axis
//input[@id='email']/parent::divChild Axis
//form/child::inputFollowing-Sibling Axis
//label[text()='Username']/following-sibling::inputAncestor Axis
//input[@id='email']/ancestor::formThese 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
Using absolute XPath for every element.
Depending on dynamic IDs that frequently change.
Creating unnecessarily long XPath expressions.
Ignoring spaces and case differences in text.
Using index-based XPath without checking element order.
Failing to verify whether the XPath identifies the intended element.
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
Website: www.paliumskills.com
Call: 8420594969 / 7044871915
WhatsApp: 9903130500
Email: info@paliumskills.com
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