0
0
Selenium Pythontesting~5 mins

CSS pseudo-classes for selection in Selenium Python

Choose your learning style9 modes available
Introduction

CSS pseudo-classes help you pick specific elements on a webpage based on their state or position. This makes testing easier and more precise.

When you want to select the first or last item in a list to check its content.
When you need to test how a button looks when hovered over or clicked.
When you want to find input fields that are currently focused during a test.
When you want to select elements that are odd or even in a group to verify styling.
When you want to test links that have been visited or not.
Syntax
Selenium Python
driver.find_element(By.CSS_SELECTOR, 'selector:pseudo-class')

Use By.CSS_SELECTOR with Selenium to apply CSS pseudo-classes.

Pseudo-classes start with a colon : after the normal CSS selector.

Examples
Selects the first <li> item inside a <ul> list.
Selenium Python
driver.find_element(By.CSS_SELECTOR, 'ul li:first-child')
Selects a button when the mouse is hovering over it (useful for visual tests).
Selenium Python
driver.find_element(By.CSS_SELECTOR, 'button:hover')
Selects an input field that currently has focus (cursor inside it).
Selenium Python
driver.find_element(By.CSS_SELECTOR, 'input:focus')
Selects all even rows in a table for testing alternate row styles.
Selenium Python
driver.find_elements(By.CSS_SELECTOR, 'tr:nth-child(even)')
Sample Program

This script opens a small HTML page with a list. It uses the :first-child pseudo-class to find the first list item and prints its text.

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

# Setup WebDriver (make sure driver executable is in PATH)

# Open a simple test page
html = '''
<html>
  <body>
    <ul>
      <li>First item</li>
      <li>Second item</li>
      <li>Third item</li>
    </ul>
  </body>
</html>
'''

# Load the HTML content
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
driver.get('data:text/html;charset=utf-8,' + html)

# Find the first list item using CSS pseudo-class
first_item = driver.find_element(By.CSS_SELECTOR, 'ul li:first-child')
print(first_item.text)

driver.quit()
OutputSuccess
Important Notes

Not all pseudo-classes work in Selenium because some depend on user interaction (like :hover), which may need special actions.

Use find_elements to get multiple elements matching a pseudo-class like :nth-child.

Always test your CSS selectors in browser DevTools first to make sure they select the right elements.

Summary

CSS pseudo-classes let you select elements based on position or state.

Use them in Selenium with By.CSS_SELECTOR for precise element selection.

They help make your tests more focused and reliable.