Last modified: Dec 05, 2023 By Alexander Williams
Python Selenium: Find Element by Class
Example 1: Find Element by Class Name
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to a webpage
driver.get('https://example.com')
# Find an element by its class name
element = driver.find_element_by_class_name('example-class')
# Perform an action on the selected element
element.click()
Output: N/A
Example 2: Find Elements by Class Name (Multiple Elements)
# Continue from the previous example
# Find multiple elements by class name
elements = driver.find_elements_by_class_name('example-class')
# Loop through the elements and perform actions
for element in elements:
element.click()
Output: N/A
Example 3: Find Element by CSS Selector with Class
# Continue from the first example
# Find an element by CSS selector with class
element = driver.find_element_by_css_selector('.example-class')
# Perform an action on the selected element
element.click()
Output: N/A
Example 4: Find Element by XPath with Class
# Continue from the first example
# Find an element by XPath with class
element = driver.find_element_by_xpath('//div[@class="example-class"]')
# Perform an action on the selected element
element.click()
Output: N/A
Example 5: Find Element by Partial Class Name
# Continue from the first example
# Find an element by partial class name
element = driver.find_element_by_partial_class_name('partial-class')
# Perform an action on the selected element
element.click()
Output: N/A
Example 6: Find Element by Chained CSS Selectors
# Continue from the first example
# Find an element using chained CSS selectors
element = driver.find_element_by_css_selector('div.example-parent-class .example-class')
# Perform an action on the selected element
element.click()
Output: N/A