Selenium is a flexible automation testing tool that provides multiple ways to locate web elements. findElement(By.className()) is one of the different types of element locators in Selenium. You can use this method in Selenium when an element has a class attribute. It allows you to select a group of elements or a specific element. You can use it to identify web elements like buttons, links, or input fields.
In this guide, we will learn about:
- What findElement(By.className()) is
- How it works in Selenium WebDriver
- Best practices and limitations
- Examples in Java, Python, and C#
What is findElement(By.className())?
It returns a ByClassName object, which internally converts the class name into a CSS selector (.classname).
This makes it easier for Selenium to locate elements on a webpage using class name.
In Selenium WebDriver, one can use findElement(By.className()) method to locate an element based on its class name attribute.
If multiple elements have the same class name, then Selenium will return the first matching element by default.
Why Use Find Element by Class In Selenium?
There are multiple reasons to use find element by class.
Simple and Efficient:
Class names are used in HTML to group similar elements like buttons, links, or sections. So it is a straightforward way to find an element by its class.
Common in Web Design:
Generally similar elements are styled together using a class name. So you can easily target all those elements using By.className().
Example:
In the above example, both buttons have the same class name submit-button. So you can easily target both of them using findElement(By.className(“submit-button”))
Readable and Easy to Maintain:
If a class name is descriptive like login-button, error-message, or product-card, and you use it in selenium tests, then it will be easy for other developers and testers to read and understand it.
When Other Selectors Are Less Reliable
Java Syntax
WebElement element = driver.findElement(By.className("your-class-name"));
Python Syntax
element = driver.find_element(By.CLASS_NAME, "your-class-name")
C# Syntax
IWebElement element = driver.FindElement(By.ClassName("your-class-name"));
Using class name in XPath
To find an element by class name attribute in Python, you can use XPath as below.
element = driver.find_element(By.XPATH, '//*[@class="class_name"]')
Here is an example to locate an element by class and ID attributes in Python selenium test script.
element = driver.find_element(By.XPATH, '//*[@id="element_id" and contains(@class, "class_name")]')
To find an element by class and name attribute in Python, you can use XPath as below.
element = driver.find_element(By.XPATH, '//*[@name="element_name" and contains(@class, "class_name")]')
You can use the below given XPath syntax in Python to locate an element using class name and text.
element = driver.find_element(By.XPATH, '//*[contains(@class, "class_name") and text()="Exact Text"]')T
How to Use findElement(By.className())
Here is a step-by-step guide to find an element using the class name.
Step 1: Get the class name of an element?
To use it, you need the class name of the element before using it in the Selenium test.
To get the class name of web element:
- Right click on element.
- Select inspect element.
- From the inspect element window, you will get a class name as shown in the below image.
Step 2: Get your test page URL
Copy the URL of the test page you are looking to test in Selenium test.
Step 3: Launch your IDE
Launch IDE as per your programming language, you use for Selenium Testing, i.e. IDLE, Visual Studio, or Eclipse.
Step 4: Create project and add selenium dependencies
To run Selenium tests, you need to create a project and add the required Selenium Jars to run Selenium tests in it.
Step 5: Run test
Here are examples of how to use find element by class in Java, Python, and C# languages.
You need to update test page URLs and class name in the following examples before running the test.
Java Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindByClass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement element = driver.findElement(By.className("example-class"));
System.out.println("Element text: " + element.getText());
driver.quit();
}
}
Python Example
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize WebDriver
driver = webdriver.Chrome()
driver.get("https://example.com")
# Locate element by class name
element = driver.find_element(By.CLASS_NAME, "example-class")
print("Element text:", element.text)
# Close browser
driver.quit()
C# Example
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
class FindByClassName
{
static void Main()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://example.com");
IWebElement element = driver.FindElement(By.ClassName("example-class"));
Console.WriteLine("Element text: " + element.Text);
driver.Quit();
}
}
Limitations:
- Works only with single-class names: Selenium does not support multiple class names. If the class attribute has multiple class names like
.
- Returns only the first matching element: If you are looking to get all elements with the same class, use findElements(By.className()) instead.
- Not recommended for dynamically generated class names: If the class name changes on every page reload, it is recommended to not use it in selenium test scripts.
- Faster than Other Methods in Some Cases: Searching by class name will be faster if multiple elements have the same tag but different attributes.
- No Need for Complex Selectors: Unlike other complex selectors like XPath or CSS, find by class name is simple. It does not require extra syntax or logic to identify the element.
- Works Well for Elements with Distinct Classes: This method will directly return the target element, if elements have a clear and unique class name.
- Avoids XPath Limitations: Sometimes XPath struggles with complex queries. Using class name will provide a simpler and more robust solution.
- findElement(By.className()) returns the first matching class element.
- findElements(By.className()) returns a list of all matching class elements.
- Make sure element exists on the page.
- Check if the class name is correct (case-sensitive).
- Wait for the element to load using WebDriverWait.
- Re-locate the element before interacting with it.
- Use WebDriverWait with EC.staleness_of(element).
- Prefer selecting elements with unique class names to avoid ambiguity.
- Prefer Selenium 4 Syntax (By.CLASS_NAME)
- Always use explicit waits to handle dynamic elements.
- Use CSS_SELECTOR or XPATH for more reliable selection.
- Check for hidden elements before interacting.
- Print logs when elements are found or actions are taken for easy debugging.
- Make sure that page is fully loaded before interacting with the element.
Advantages:
Frequently Asked Questions (FAQs)
Question: What is finding element by class name in Selenium?
Answer: findElement(By.className()) is a Selenium WebDriver method that is used to locate an element using its class name.
Question: How do I find an element by class name in Selenium?
Answer: You can use the following syntax
driver.find_element(By.CLASS_NAME, "your_class_name")
Question: What is the difference between findElement(By.className()) and findElements(By.className())?
Answer:
Question: Can I use multiple class names in findElement(By.className())?
Answer: No, Selenium does not support compound class names. You can use CSS selector instead like:
driver.find_element(By.CSS_SELECTOR, ".classx.classy")
Question: Why is find_element_by_class_name deprecated?
Answer: Selenium 4 removed find_element_by_class_name. Now, you can use driver.find_element(By.CLASS_NAME, “your_class_name”).
Question: How do I click an element found by class name?
Answer: After finding the element, use: element.click() in your selenium test.
Question: How do I get text from an element found by class name?
Answer: Use given syntax below to get text:
text = driver.find_element(By.CLASS_NAME, "your_class_name").text
Question: Can I use findElement(By.className()) for hidden elements?
Answer: No, Selenium cannot interact with hidden elements.
Question: How do I check if an element exists before finding it?
Answer: You can use the following syntax:
elements = driver.find_elements(By.CLASS_NAME, "your_class_name")
if elements:
print("Element found!")
Question: What’s the best alternative if find element by class name fails?
Answer: CSS_SELECTOR is the best alternative.
Question: Can I use regex with find element by class name?
Answer: No, but you can use XPATH with contains():
driver.find_element(By.XPATH, "//*[contains(@class, 'partial_class_name')]")
Troubleshooting Common find element by class Errors
Error: ❌ NoSuchElementException: Unable to locate element.
Fix: ✅ You need to check the following things to resolve this error.
Error: ❌ InvalidSelectorException: Compound class names not permitted.
.
To fix this error, you can use an alternative element locator like CSS Selector. Example:
driver.find_element(By.CSS_SELECTOR, ".class1.class2")
Error: ❌ StaleElementReferenceException: Stale element reference
Fix: ✅ This error occurs when an element is no longer attached to the DOM.
To fix this:
Error: ❌ AttributeError: ‘WebDriver’ object has no attribute ‘find_element_by_class_name’.
Fix: ✅ Actually, find_element_by_class_name is deprecated in Selenium 4.
Now in Selenium 4, you can use:
driver.find_element(By.CLASS_NAME, "class_name")
Error: ❌ ElementClickInterceptedException
Fix: ✅ This error occurs when another element is blocking the target element.
To resolve this issue, you can use JavaScriptExecutor to force-click:
driver.execute_script("arguments[0].click();", element)
Error: ❌ TimeoutException: element not found within time.
Fix: ✅ This error occurs when an element is taking time to load.
To fix this error, use WebDriverWait to wait until it appears:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "class_name")))
Error: ❌ TypeError: find_element_by_class_name() missing 1 required positional argument
Fix: ✅ This error occurs when you pass class name incorrectly. Pass the class name correctly:
driver.find_element(By.CLASS_NAME, "your_class_name")
Error: ❌ Multiple elements found when expecting a single element.
Fix: ✅ This error occurs when you use driver.find_element and return multiple elements. In this case, you can use driver.find_elements in Selenium 4.
driver.find_elements(By.CLASS_NAME, "your_class_name")
Error: ❌ NoneType object has no attribute ‘click’
Fix: ✅ Targeted element was not found, so it returned None. In this case, you need to verify the class name or add an explicit wait before interacting with the element.
Error: ❌ find_element(By.class_name) works in one browser but not another.
Fix: ✅ Different browsers render elements differently. If the find element by class name is not working in a specific browser, then you can try CSS_SELECTOR or XPATH as an alternative.
Best Practices for Find By Class
Here are a few important points you need to consider while using Find By Class in Selenium WebDriver automation test.
Pro Tip: If you often struggle with class selectors, consider using CSS_SELECTOR or XPATH especially for complex DOM structures.
Now you’re all set to use find by class in Selenium tests without errors!
Have any questions? Drop a comment below! I am ready to help you with.