Last modified: Dec 02, 2023 By Alexander Williams

Python Selenium: CSS Selector - Examples

Example 1: Select Element by ID


from selenium import webdriver

# Create a Chrome driver
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get('https://example.com')

# Use CSS selector to select an element by ID
element = driver.find_element_by_css_selector('#example-id')

# Perform an action on the selected element
element.click()

# Close the browser
driver.quit()

Example 2: Select Element by Class Name


from selenium import webdriver

# Create a Chrome driver
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get('https://example.com')

# Use CSS selector to select an element by class name
element = driver.find_element_by_css_selector('.example-class')

# Perform an action on the selected element
element.click()

# Close the browser
driver.quit()

Example 3: Select Element by Attribute


from selenium import webdriver

# Create a Chrome driver
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get('https://example.com')

# Use CSS selector to select an element by attribute
element = driver.find_element_by_css_selector('[data-example="value"]')

# Perform an action on the selected element
element.click()

# Close the browser
driver.quit()

Example 4: Select Nth Child


from selenium import webdriver

# Create a Chrome driver
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get('https://example.com')

# Use CSS selector to select the second child of a parent element
element = driver.find_element_by_css_selector('ul li:nth-child(2)')

# Perform an action on the selected element
element.click()

# Close the browser
driver.quit()

Example 5: Select Element by Descendant


from selenium import webdriver

# Create a Chrome driver
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get('https://example.com')

# Use CSS selector to select a descendant element
element = driver.find_element_by_css_selector('div .example-class')

# Perform an action on the selected element
element.click()

# Close the browser
driver.quit()