Q9 of 37 · Selenium
What is the difference between absolute and relative XPath?
Short answer
Short answer: Absolute XPath starts from the document root with `/html/body/...` and depends on the full DOM hierarchy — fragile. Relative XPath starts with `//` and matches anywhere in the tree, usually anchored to a stable attribute or text. Always prefer relative.
Detail
Absolute XPath is a literal path from the document root: /html/body/div[2]/div/form/div[3]/input. It's exact, but a single element added or moved anywhere in the path breaks it. Browser DevTools' "Copy XPath" gives you absolute by default — and that's why beginners' XPath locators are notoriously fragile.
Relative XPath starts with //, which means "match anywhere in the document": //input[@name='email']. It's anchored to what the element is (an attribute, text, role), not where it sits in the tree. UI refactors that don't touch the email input leave it intact.
A few patterns worth knowing:
- Attribute match:
//button[@data-test='submit'] - Text match:
//a[text()='Sign in'] - Contains:
//div[contains(@class, 'error')]— partial match for class lists. - Ancestor / sibling:
//label[text()='Email']/following-sibling::input— useful when the form has no properforattribute on labels. - Logical operators:
//input[@name='email' and @required]
The senior takeaway: when CSS can't express what you need (text matching, traversals like "input next to a specific label"), reach for relative XPath. Never copy absolute XPath out of DevTools and check it in — that's how suites become unmaintainable.
// EXAMPLE
// Fragile — breaks if a div is added above
driver.findElement(By.xpath("/html/body/div[2]/form/input[1]"));
// Stable — matches the email input wherever it sits
driver.findElement(By.xpath("//input[@data-test='email']"));
// Useful relative pattern: input adjacent to a labelled text
driver.findElement(By.xpath(
"//label[text()='Email']/following-sibling::input"
));