Absolute and partial Xpath

Table of Contents

When you step into the world of Selenium tutorials, one of the first and most essential concepts you’ll encounter is XPath. XPath, short for XML Path Language, plays a crucial role in identifying and navigating elements within a webpage’s Document Object Model (DOM). Whether you’re preparing for an Automation testing training session or pursuing your test Automation certification, understanding XPath especially Absolute and Partial (or Relative) XPath is a must.

In this blog, we’ll explore what XPath is, why it’s used, the difference between Absolute and Partial XPath, practical examples, pros and cons, and real-world use cases that strengthen your Selenium test scripts.

What is XPath in Selenium?

XPath (XML Path Language) is a query language used to locate elements in an XML or HTML document. In Selenium WebDriver, XPath acts as a powerful locator technique that helps you find any element on a webpage even when other locators like ID, Name, or Class aren’t available.

When testing complex web applications, sometimes developers don’t assign unique IDs or Names to every element. XPath bridges this gap by allowing testers to create expressions to navigate through the DOM tree and accurately target elements.

Example:

WebElement button = driver.findElement(By.xpath("//button[@id='loginBtn']"));
button.click();

Here, XPath is used to locate a button element using its attribute id='loginBtn'.

Why XPath is Important in Selenium Tutorials

XPath provides flexibility and precision in locating elements, which makes it invaluable for professionals undergoing automation testing training. Here’s why:

  1. Dynamic element identification – Handles elements without fixed IDs or names.
  2. DOM traversal – Enables navigation between parent, child, and sibling nodes.
  3. Complex queries – Supports conditional logic, multiple attributes, and text matching.
  4. Cross-browser reliability – Works consistently across Chrome, Firefox, Edge, and Safari.
  5. Foundation for automation scripts – A core concept covered in every test automation certification program.

Types of XPath in Selenium

There are two types of XPath expressions used in Selenium:

  1. Absolute XPath (Full Path)
  2. Partial XPath (Relative Path)

Let’s break each of them down.

What is Absolute XPath?

Absolute XPath defines the complete path from the root element of the HTML document (<html>) to the desired element. It navigates step-by-step through all nodes in the DOM hierarchy.

Example:

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

Here, the XPath begins from the <html> root tag and travels through every nested tag to reach the input field.

Key Characteristics:

  • Always starts with a single slash ( / ).
  • Follows a fixed hierarchical path.
  • Changes in page structure can break this XPath.

Advantages of Absolute XPath:

  • Simple to generate (you can right-click > Copy XPath in Chrome DevTools).
  • Useful for static pages where the structure rarely changes.
  • Provides a clear map of the element’s location in the DOM.

Disadvantages:

  • Highly fragile – even a small UI change can make it invalid.
  • Less maintainable for large or dynamic web applications.
  • Not recommended for professional automation testing training projects or real-time scripts.

What is Partial (Relative) XPath?

Partial XPath, also known as Relative XPath, starts from any element within the HTML structure rather than the root. It’s more flexible and dynamic compared to Absolute XPath.

Example:

//input[@id='username']

Here, the XPath starts with //, meaning it can search for the element anywhere in the DOM.

Key Characteristics:

  • Always starts with a double slash ( // ).
  • Does not depend on the element’s exact position.
  • More reliable and resilient to structural changes.

Advantages of Partial XPath:

  • More maintainable — unaffected by minor DOM changes.
  • Easy to write and read.
  • Can combine multiple attributes or conditions for dynamic elements.
  • Preferred in test automation certification and real-world Selenium frameworks.

Disadvantages:

  • Slightly slower than Absolute XPath since it searches the entire DOM.
  • Can become complex if written without proper strategy or filters.

Syntax Rules for Writing XPath Expressions

Both Absolute and Partial XPath use the same syntax rules but differ in their starting points. Here are a few syntax examples used in selenium tutorials:

Expression TypeExampleDescription
Attribute-based//input[@name='email']Locates element by attribute
Text-based//button[text()='Login']Locates element by visible text
Contains()//a[contains(text(),'Learn More')]Matches partial text
Starts-with()//input[starts-with(@id,'user')]Matches partial attribute value
AND condition//input[@type='text' and @name='email']Matches multiple attributes
OR condition//input[@type='text' or @name='username']Matches one of two attributes

These techniques make XPath extremely versatile and are a major component of automation testing training programs.

Absolute vs Partial XPath: Key Differences

FeatureAbsolute XPathPartial (Relative) XPath
Starting pointRoot element (/html)Anywhere in the DOM (//)
Syntax symbolSingle slash /Double slash //
FlexibilityLowHigh
MaintenanceDifficultEasy
SpeedFaster (for small DOMs)Slightly slower
RobustnessBreaks with structure changeWorks even with layout changes
Use caseStatic pagesDynamic, real-world applications

When preparing for test automation certification, understanding this table helps you decide which type of XPath suits a given scenario.

Practical Examples of Absolute and Partial XPath in Selenium

Let’s consider a login page example.

Example HTML:

<html>
  <body>
    <div class="container">
      <form id="loginForm">
        <input type="text" id="username" name="user">
        <input type="password" id="password" name="pass">
        <button id="loginBtn">Login</button>
      </form>
    </div>
  </body>
</html>

Using Absolute XPath:

WebElement userField = driver.findElement(By.xpath("/html/body/div/form/input[1]"));

Using Partial XPath:

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

If the developer adds another <div> above <form>, the Absolute XPath will fail, but the Partial XPath remains valid.

Advanced Partial XPath Functions for Professionals

Professionals undergoing automation testing training often use advanced XPath functions to handle complex, dynamic web elements.

1. contains()

Used when attribute values change dynamically.

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

2. starts-with()

Identifies elements whose attributes begin with specific characters.

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

3. text()

Matches visible text.

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

4. normalize-space()

Used to handle unwanted white spaces.

//span[normalize-space(text())='Submit']

These functions are heavily covered in selenium tutorials and test automation certification courses to improve XPath precision.

Best Practices for Using XPath in Selenium

  1. Prefer Relative XPath: Use Partial XPath wherever possible.
  2. Avoid hardcoding indexes: Instead of /div[3]/button[2], use attribute-based locators.
  3. Leverage developer tools: Chrome DevTools > Inspect > Copy XPath.
  4. Combine attributes: Use and/or for better accuracy.
  5. Test in the browser console: Validate your XPath using $x("your_xpath") before adding it to scripts.
  6. Keep locators readable: Maintain a naming convention for clarity and collaboration.
  7. Re-use XPaths: Store common XPaths in a separate object repository file.
  8. Focus on maintainability: Avoid brittle locators that break frequently.

Real-World Application of XPath in Automation Testing

In real-world automation testing training, XPath is used to:

  • Automate complex form submissions.
  • Validate dynamic dropdowns, checkboxes, and popups.
  • Navigate through web tables for data extraction.
  • Locate hidden or dynamically loaded elements using AJAX.
  • Build robust test frameworks like Page Object Model (POM) or Data-Driven Testing (DDT).

Professionals who master XPath gain a competitive advantage when preparing for test automation certification exams or applying for QA automation roles.

Example: XPath in a Selenium Test Script

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

public class XPathExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com/login");

        // Using Relative XPath
        WebElement username = driver.findElement(By.xpath("//input[@id='username']"));
        WebElement password = driver.findElement(By.xpath("//input[@id='password']"));
        WebElement loginButton = driver.findElement(By.xpath("//button[text()='Login']"));

        username.sendKeys("admin");
        password.sendKeys("admin123");
        loginButton.click();

        driver.quit();
    }
}

This example showcases clean and maintainable Partial XPaths, perfect for selenium tutorials or automation testing training demos.

Summary: Choosing the Right XPath for the Right Scenario

ScenarioRecommended XPath Type
Static page or prototypeAbsolute XPath
Dynamic or frequently updated UIPartial (Relative) XPath
Elements without unique IDsAttribute-based Relative XPath
Quick debugging or one-time scriptsAbsolute XPath
Large-scale frameworks (POM, DDT)Partial XPath with logical conditions

Conclusion

XPath remains one of the most vital topics in Selenium, forming the foundation of every automation testing training and test automation certification program. Understanding both Absolute and Partial XPath empowers testers to design more reliable, adaptable, and future-proof test scripts.If you’re currently exploring selenium tutorials, invest time mastering XPath functions, axes, and advanced filtering techniques. It’s a skill that separates beginner testers from professional automation engineers.

With consistent practice, you’ll not only improve test accuracy but also gain the confidence to handle complex UI automation challenges a key milestone toward achieving your test automation certification.

Share this article

Enroll Free demo class
Enroll IT Courses

Enroll Free demo class

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Join Free Demo Class

Let's have a chat