0
0
Selenium Pythontesting~10 mins

XPath axes (parent, child, sibling) in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies locating elements using XPath axes: parent, child, and sibling. It checks if the test can find a child element, then its parent, and a sibling element correctly on a sample webpage.

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 TestXPathAxes(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/xpath-axes-sample')

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

        # Find child element using child axis
        child = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@id='parent']/child::span[@class='child']")))
        self.assertEqual(child.text, 'Child Element')

        # Find parent element using parent axis
        parent = child.find_element(By.XPATH, "parent::div")
        self.assertEqual(parent.get_attribute('id'), 'parent')

        # Find sibling element using following-sibling axis
        sibling = child.find_element(By.XPATH, "following-sibling::span[@class='sibling']")
        self.assertEqual(sibling.text, 'Sibling Element')

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window opens and navigates to https://example.com/xpath-axes-sample-PASS
2Waits until child element located by XPath using child axis is presentPage loaded with a div#parent containing span.child and span.sibling elementsChecks child.text equals 'Child Element'PASS
3Finds parent element of child using parent axis XPathParent div element with id='parent' foundChecks parent.get_attribute('id') equals 'parent'PASS
4Finds sibling element of child using following-sibling axis XPathSibling span element with class='sibling' found next to childChecks sibling.text equals 'Sibling Element'PASS
5Browser closes and test endsBrowser window closed-PASS
Failure Scenario
Failing Condition: If the XPath does not locate the expected element (child, parent, or sibling) due to incorrect XPath or page structure changes
Execution Trace Quiz - 3 Questions
Test your understanding
Which XPath axis is used to find the parent element of a given node?
Afollowing-sibling
Bchild
Cparent
Ddescendant
Key Result
Using XPath axes like parent, child, and sibling helps navigate complex page structures precisely, making tests more robust and easier to maintain.