0
0
Selenium Pythontesting~10 mins

CSS pseudo-classes for selection in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage with a list of items and verifies that the first item is selected using the CSS pseudo-class :first-child. It checks that the correct element is found and its text matches the expected value.

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

    def test_first_child_selection(self):
        driver = self.driver
        wait = WebDriverWait(driver, 10)
        # Wait until the list is present
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'ul#items-list')))
        # Find the first child li element using :first-child pseudo-class
        first_item = driver.find_element(By.CSS_SELECTOR, 'ul#items-list > li:first-child')
        # Assert the text of the first item is as expected
        self.assertEqual(first_item.text, 'Item 1')

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsTest framework initializes and prepares to run the test-PASS
2Browser opens ChromeChrome browser window opens, ready to navigate-PASS
3Navigates to 'https://example.com/list'Page with a list of items loads in the browser-PASS
4Waits until the unordered list with id 'items-list' is presentThe list element is present in the DOMPresence of element located by CSS selector 'ul#items-list'PASS
5Finds the first list item using CSS selector 'ul#items-list > li:first-child'The first <li> element inside the list is found-PASS
6Checks that the text of the first item is 'Item 1'The text content of the first list item is 'Item 1'Assert that first_item.text == 'Item 1'PASS
7Test ends and browser closesBrowser window closes, test completes-PASS
Failure Scenario
Failing Condition: The first list item is not found or its text does not match 'Item 1'
Execution Trace Quiz - 3 Questions
Test your understanding
Which CSS pseudo-class is used to select the first child element in this test?
A:first-child
B:last-child
C:nth-child(2)
D:hover
Key Result
Use CSS pseudo-classes like :first-child to select specific elements precisely. Combine this with explicit waits to ensure elements are present before interacting, improving test reliability.