0
0
Selenium Pythontesting~5 mins

Absolute vs relative XPath in Selenium Python

Choose your learning style9 modes available
Introduction

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

When you want to find an element by its full path in the webpage structure.
When the webpage structure changes often and you want a flexible way to find elements.
When you need to locate elements without unique IDs or classes.
When debugging why a test can't find an element.
When writing tests that must work on different page layouts.
Syntax
Selenium Python
Absolute XPath: /html/body/div[1]/div[2]/button
Relative XPath: //button[@id='submit']
Absolute XPath starts from the root of the page and follows the full path.
Relative XPath starts from anywhere and uses conditions to find elements.
Examples
Absolute XPath: Finds the first input inside the form inside the second div of the body.
Selenium Python
/html/body/div[2]/form/input[1]
Relative XPath: Finds any input element with the name 'username' anywhere on the page.
Selenium Python
//input[@name='username']
Relative XPath: Finds a link with text 'Home' inside any div with class 'menu'.
Selenium Python
//div[@class='menu']//a[text()='Home']
Sample Program

This script opens a webpage and finds the main heading using both absolute and relative XPath. It prints the text found by each method.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()
driver.get('https://example.com')

# Using absolute XPath to find the heading
absolute_element = driver.find_element(By.XPATH, '/html/body/div/h1')
print('Absolute XPath text:', absolute_element.text)

# Using relative XPath to find the heading
relative_element = driver.find_element(By.XPATH, '//h1')
print('Relative XPath text:', relative_element.text)

driver.quit()
OutputSuccess
Important Notes

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

Relative XPath is more flexible and easier to maintain.

Prefer relative XPath for most test automation tasks.

Summary

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

Relative XPath starts anywhere and uses conditions to find elements.

Relative XPath is usually better for stable and maintainable tests.