CSS pseudo-classes help you pick specific elements on a webpage based on their state or position. This makes testing easier and more precise.
CSS pseudo-classes for selection in 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.
<li> item inside a <ul> list.driver.find_element(By.CSS_SELECTOR, 'ul li:first-child')driver.find_element(By.CSS_SELECTOR, 'button:hover')driver.find_element(By.CSS_SELECTOR, 'input:focus')driver.find_elements(By.CSS_SELECTOR, 'tr:nth-child(even)')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.
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()
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.
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.