Testim Copilot is here | Learn More

How To Find Elements by Class in Selenium: A Practical Guide

Selenium is a popular browser automation tool. Using Selenium, you can automate almost every action a regular user can perform…

Testim
By Testim,

Selenium is a popular browser automation tool. Using Selenium, you can automate almost every action a regular user can perform on a web browser. For example, with Selenium, you can write a small script that can open a webpage and then complete a form on the page.

However, to carry out an operation like this, Selenium will first need a way to locate each element on the form. Selenium needs to find each input field first before it can enter text in them.

Luckily, Selenium offers a few methods you can use to find elements.

One of the options the Selenium WebDriver library provides for locating HTML elements is the use of the class property.

The HTML class property is used for setting a class to an HTML element. One use of the class property is applying styles to elements via CSS. You can also use classes to interact with specific elements in your JavaScript code.

It is common practice for multiple elements to have the same value for the class. As such, any style you define for the class applies to all the elements. This is also the same for JavaScript code that refers to the class.

In this post, you’ll learn how to find elements by class in Selenium by walking through a practical example.

Selenium By.class() Method

This method makes it possible to locate an element by referencing its class name. The class() method is found inside the By class of the Selenium WebDriver JavaScript library. The class also contains other alternative methods for locating elements.

The Selenium WebDriver library for other programming languages has a similar method for locating elements. For example, the Python library finds elements by class name using the CLASS_NAME constant from its By class. The following code snippets show the Selenium element locator method for Python, Java, and JavaScript:

Python

loginBtn = driver.find_element(By.CLASS_NAME, "login")

Java

WebElement loginBtn = driver.findElement(By.class("login"));

JavaScript

let loginBtn = await driver.findElement(By.class('login'));

In later sections, we’ll look at a more detailed example of this selector in action.

Prerequisites

Before we continue, make sure to have the following so you can follow along better:

  • a working setup of Selenium and WebDriver on your machine
  • basic knowledge of JavaScript (or any other language that WebDriver supports)

For this post, we assume that you are already familiar with setting up Selenium, and you can write code in your preferred language to control the browser using Selenium. As a result, we won’t be including steps for setting up Selenium.

Steps

For this post, we’ll write a small script that finds hyperlinks on a webpage. We’ll be finding the <a> element associated with a specific link using its class property. After that, we’ll perform a click action on the link.

We’ll be using JavaScript throughout our example. So, let’s dive into the actual steps.

1. Create Script File

First, we need to create a new file where we’ll be writing the code for our script. To do that, create a new file inside the directory where you wish to run Selenium from and save the file as example.js.

Note: Make sure you already have the Selenium Node package installed in the directory. If you’re starting with a new, empty directory, you can install the package by running the following code in terminal or command prompt:

npm init -y
npm install selenium-webdriver

The above step will be different if you use Selenium with another programming language that isn’t JavaScript. You can find more specific instructions for other languages on the official documentation page for the language.

2. Create Webpage for Test

Before writing the code for finding elements by class in Selenium, let’s create the HTML page we’ll be loading.

Create a new file in the same directory as the first step and save the file as testpage.html. Then, add the following code to the file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test page</title>
</head>
<body>
<ul>
    <li><a href="https://testim.io" class="link">Testim</a></li>
</ul>
</body>
</html>

From the above code, we have a basic HTML document that includes a hyperlink. The hyperlink has the value for class property set to “link.” In the next step, we’ll learn how to find this hyperlink in Selenium using its class property.

3. Add Code for Selenium

Now we’re set to start writing some JavaScript code. We’ll be creating a script that finds elements using their class property.

Open the example.js file you created earlier in step one, then add the following code to it:

const {Builder, By, Key, until} = require('selenium-webdriver');

(async ()=> {
    let driver = await new Builder().forBrowser('chrome').build();
    const URI = 'file:///Users/ea/Development/tutorial-examples/selenium-by-class/testpage.html';
    await driver.get(URI);

    await driver.wait(until.elementLocated(By.className('link')), 1000);

    const footerLink = await driver.findElement(By.className('link'));
    footerLink.click();

})();

The above code will initialize a new instance of WebDriver using Google Chrome. You can change the default browser to your preferred browser by changing the parameter for the forBrowser() method. For example, using forBrowser(“firefox”) will run the same tasks using Firefox.

Next, we’ll set a URI for the webpage we wish to open with Selenium.

Note: Make sure to replace the value for URI with the full path to testpage.html on your computer.

After launching the browser, Selenium will wait until the element with class “link” is found. We achieve this by using until.elementLocated() and the By.className() methods.

Next, using findElement() and the By.className() method again, Selenium finds the element with class “link.” And finally, Selenium performs a click operation on the element using the click() action.

4. Running the Script

Now that we’ve set up the test webpage and our Selenium script, let’s run the script.

To do that, run the following code in terminal or command prompt:

node example.js

If you followed all the steps without any issue, the above command would open a new Chrome window that loads testpage.html. Once the page is loaded, Selenium will locate the link with class “link” and then perform a click on the link. You can see the result in the following image:

selenium find element by class

Remember, we mentioned earlier that multiple elements could have the same class name, and any style we define for the class applies to all the elements.

By default, Selenium’s actions do not behave similarly. That’s to say, if we have a webpage with multiple input fields with the same class name and we find an element using class and then perform an action, the action will only apply to the first element.

Conclusion

Selenium is a popular tool for browser automation. It supports many browsers and programming languages, thus offering more flexibility for developers and testers.

We used Selenium to automate opening a web page and using JavaScript and Chrome in this post. You can do much more and use your favorite languages. However, for the scope of this post, our focus was on finding HTML elements using the class property.

Though Selenium is beneficial and flexible, the initial setup can be stressful. In addition, performing complex tasks will require writing more complex code. Also, because the primary method for using Selenium involves writing code, you may spend extra time debugging extra code to test your app.

Testim offers an alternative to reduce the stress associated with setup and complexity in writing browser automation code. You can try Testim for free here.

What to read next

Step-by-Step Selenium: Wait Until Element Is Visible

Selenium Grid 4: A Beginner’s Tutorial