0
0
Selenium Pythontesting~5 mins

Find element by class name in Selenium Python

Choose your learning style9 modes available
Introduction

Finding an element by its class name helps you interact with parts of a webpage easily, like clicking a button or reading text.

You want to click a button that has a specific style class.
You need to check if a message with a certain class appears on the page.
You want to fill a form field identified by its class.
You want to verify that an element with a certain class is visible.
You want to extract text from an element styled with a specific class.
Syntax
Selenium Python
element = driver.find_element(By.CLASS_NAME, "class_name")

Use By.CLASS_NAME to specify you are searching by class.

Replace "class_name" with the actual class value from the webpage.

Examples
Finds the first element with class submit-button.
Selenium Python
element = driver.find_element(By.CLASS_NAME, "submit-button")
Finds the first element with class error-message to check for errors.
Selenium Python
element = driver.find_element(By.CLASS_NAME, "error-message")
Finds the first navigation item by its class nav-item.
Selenium Python
element = driver.find_element(By.CLASS_NAME, "nav-item")
Sample Program

This script opens a webpage, tries to find the first element with class example (which may not exist), prints 'Element not found.' if not found, then closes the browser.

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

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open example page
driver.get("https://www.example.com")

try:
    # Find element by class name
    element = driver.find_element(By.CLASS_NAME, "example")
    print("Element found with class 'example':", element.text)
except Exception as e:
    print("Element not found.")

# Wait a bit to see the browser
time.sleep(2)

# Close browser
driver.quit()
OutputSuccess
Important Notes

Class names should not contain spaces; if the element has multiple classes, use one class at a time.

If multiple elements share the same class, find_element returns the first one found.

Use find_elements(By.CLASS_NAME, "class_name") to get all elements with that class.

Summary

Use find_element(By.CLASS_NAME, "class_name") to locate elements by their class.

This helps interact with webpage parts like buttons or messages easily.

Remember it finds the first matching element only.