Last modified: Nov 15, 2023 By Alexander Williams
Python Selenium: Click Button by CSS Selector
Table Of Contents
Example 1: Click Button by ID
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to the webpage
driver.get('https://example.com')
# Click the button using its ID
button = driver.find_element_by_css_selector('#button-id')
button.click()
# Close the browser
driver.quit()
Example 2: Click Button by Class Name
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to the webpage
driver.get('https://example.com')
# Click the button using its class name
button = driver.find_element_by_css_selector('.button-class')
button.click()
# Close the browser
driver.quit()
Example 3: Click Nth Button in a List
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to the webpage
driver.get('https://example.com')
# Click the third button in a list using :nth-child
button = driver.find_element_by_css_selector('.button-list:nth-child(3)')
button.click()
# Close the browser
driver.quit()
Example 4: Click Button Inside a Specific Container
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to the webpage
driver.get('https://example.com')
# Click the button inside a specific container
button = driver.find_element_by_css_selector('.container-class #nested-button')
button.click()
# Close the browser
driver.quit()
Example 5: Click Button with Attribute Value
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to the webpage
driver.get('https://example.com')
# Click the button with a specific attribute value
button = driver.find_element_by_css_selector('[data-action="submit"]')
button.click()
# Close the browser
driver.quit()
Example 6: Click Button with Partial Attribute Value
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to the webpage
driver.get('https://example.com')
# Click the button with a partial attribute value
button = driver.find_element_by_css_selector('[data-action^="like"]')
button.click()
# Close the browser
driver.quit()