0
0
Selenium Javatesting~5 mins

Absolute vs relative XPath in Selenium Java

Choose your learning style9 modes available
Introduction

XPath helps find elements on a web page. Absolute and relative XPath are two ways to locate these elements.

When you want to find an element by its full path from the page root.
When the page structure is simple and unlikely to change.
When you want a shorter, flexible path to an element.
When the page layout changes often and you want stable locators.
When you need to locate elements by attributes or partial paths.
Syntax
Selenium Java
Absolute XPath: /html/body/div[1]/div[2]/input
Relative XPath: //input[@id='username']
Absolute XPath starts from the root element and follows the full path.
Relative XPath starts from anywhere in the document and uses // to search.
Examples
This is an absolute XPath. It starts from the root html and goes down the tree step by step.
Selenium Java
/html/body/div[1]/div[2]/input
This is a relative XPath. It finds any input element with an id of 'username' anywhere on the page.
Selenium Java
//input[@id='username']
Relative XPath that finds an a tag with text 'Home' inside a div with class 'menu'.
Selenium Java
//div[@class='menu']//a[text()='Home']
Sample Program

This Java Selenium code opens a login page and finds the username input field using both absolute and relative XPath. It prints the 'name' attribute of the found elements.

Selenium Java
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) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com/login");

        // Using absolute XPath
        WebElement absoluteElement = driver.findElement(By.xpath("/html/body/div[1]/form/input[1]"));
        String absoluteValue = absoluteElement.getAttribute("name");

        // Using relative XPath
        WebElement relativeElement = driver.findElement(By.xpath("//input[@name='username']"));
        String relativeValue = relativeElement.getAttribute("name");

        System.out.println("Absolute XPath found element with name: " + absoluteValue);
        System.out.println("Relative XPath found element with name: " + relativeValue);

        driver.quit();
    }
}
OutputSuccess
Important Notes

Absolute XPath is fragile. If the page layout changes, it may break.

Relative XPath is more flexible and preferred for most tests.

Use attributes and text in relative XPath to make locators stable and readable.

Summary

Absolute XPath starts from the root and follows the full path.

Relative XPath starts anywhere and uses // to find elements by attributes or text.

Relative XPath is usually better for stable and maintainable tests.