0
0
Selenium Pythontesting~10 mins

Absolute vs relative XPath in Selenium Python - Test Execution Compared

Choose your learning style9 modes available
Test Overview

This test opens a webpage and locates a button using both absolute and relative XPath. It verifies that the button is clickable and has the expected text.

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest

class TestXPath(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/testpage')

    def test_button_xpath(self):
        driver = self.driver
        wait = WebDriverWait(driver, 10)

        # Locate button using absolute XPath
        abs_xpath = '/html/body/div/main/section/button'
        button_abs = wait.until(EC.element_to_be_clickable((By.XPATH, abs_xpath)))
        self.assertEqual(button_abs.text, 'Click Me')

        # Locate button using relative XPath
        rel_xpath = '//section/button'
        button_rel = wait.until(EC.element_to_be_clickable((By.XPATH, rel_xpath)))
        self.assertEqual(button_rel.text, 'Click Me')

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open, ready to load the test page-PASS
2Browser navigates to 'https://example.com/testpage'Page loads with a main section containing a button labeled 'Click Me'-PASS
3Wait until the button is clickable using absolute XPath '/html/body/div/main/section/button'Button element is found and clickableCheck that button text equals 'Click Me'PASS
4Wait until the button is clickable using relative XPath '//section/button'Button element is found and clickableCheck that button text equals 'Click Me'PASS
5Test ends and browser closesBrowser window closes-PASS
Failure Scenario
Failing Condition: The XPath does not locate the button because the page structure changed or XPath is incorrect
Execution Trace Quiz - 3 Questions
Test your understanding
Which XPath is more fragile to page structure changes?
ABoth are equally fragile
BAbsolute XPath
CRelative XPath
DNeither is fragile
Key Result
Using relative XPath is a best practice because it is less likely to break when the page layout changes, making tests more stable.