Introduction
XPath helps find elements on a webpage. Absolute and relative XPath are two ways to locate these elements.
XPath helps find elements on a webpage. Absolute and relative XPath are two ways to locate these elements.
Absolute XPath: /html/body/div[1]/div[2]/button Relative XPath: //button[@id='submit']
/html/body/div[2]/form/input[1]
//input[@name='username']
//div[@class='menu']//a[text()='Home']
This script opens a webpage and finds the main heading using both absolute and relative XPath. It prints the text found by each method.
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()
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.
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.
<div>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>//ul/li[2] select?/html/body/div/button[@id='login']<div class='product'> <span class='name'>Product A</span> <span class='price'>$20</span> </div> <div class='product'> <span class='name'>Product B</span> <span class='price'>$30</span> </div>
Pass the test and this pattern moves unknown