DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Linked List Popular Problems Vol. 1
  • Java: Why a Set Can Contain Duplicate Elements
  • What Is Ant, Really?
  • DataWeave Interview Question: Concatenate Elements of an Array

Trending

  • A Modern Stack for Building Scalable Systems
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  1. DZone
  2. Coding
  3. Java
  4. Java Class Name Locator in Selenium

Java Class Name Locator in Selenium

Learn more about using the Java Class name locator in Selenium.

By 
Sadhvi Singh user avatar
Sadhvi Singh
·
Updated Jun. 26, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
32.4K Views

Join the DZone community and get the full member experience.

Join For Free

The CSS Locator in Selenium is one of the most important aspects of writing a script. If you cannot locate an element by using any CSS locator in Selenium, then being proficient at Selenium automation will be a tough task. Selenium provides multiple ways of locating an element.

I have written a complete guide to help illustrate the practical demonstration of CSS locator in Selenium.

In this Selenium Java tutorial, I will be referencing on Class name locator in Selenium to demonstrate how to locate an element on a webpage via class name.

Getting Started With Class Name Locator in Selenium With Example

Next, in this Selenium Java tutorial, we will consider the scenario of Airbnb, where we intend to locate the ‘Where’ field in the search form of Airbnb homepage via class name. Below is a screenshot of Airbnb page where we inspect the ‘Where’ field in the form.
image:
Locator In Selenium

In-order to use Class name locator in Selenium, we need to use the below syntax:
findElement(By.className("_up0kwni "))

Now, let’s look into the code for finding elements by Class name in locators:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClassNameLocator {
    public static void main(String[] args) { // TODO Auto-generated method stub                  
  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");         
  WebDriver driver=new ChromeDriver();         
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);                  
  driver.manage().window().maximize();                  //Opening the air bnb home page         
  driver.get("https://www.airbnb.co.in/");                  //Locating location field for the search  form via class name         
  driver.findElement(By.className("_up0kwni")).sendKeys("Goa", Keys.ENTER);           
  //Locating check-in field for the search  form via class name         
  driver.findElement(By.className("_14fdu48d")).click();  
  //Locating the date 12th June for check-in field         
  driver.findElement(By.className("_1wh4xpp1")).click(); 
  //closing the driver         
  driver.quit();                                      
}     
}


Pretty simple, isn’t it? In the upcoming session of this Java Selenium tutorial, we will learn how to handle a common exception for class name locator in Selenium.

One of the Most Common Exceptions for Class Name Locator in Selenium

Another interesting fact and a popular error you may come across while using Class name locator in Selenium would be something like:

locators in selenium

I am sure you have come across this error. Let's try to incorporate this scenario in the following code snippet for the Facebook sign-up page. Below is the DOM structure for facebook ‘first name’ field with class name attribute highlighted below:

locators in selenium

Check out the Referenced code snippet where we try to access the first name field using the class name locator in Selenium:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClassNameLocator {
    public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub                  
  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");         
  WebDriver driver=new ChromeDriver();         
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);                  
  driver.manage().window().maximize();                  //Opening the air bnb home page         
  driver.get("https://www.facebook.com/");                  //Locating by firstname via class name         
  driver.findElement(By.className("inputtext _58mg _5dba _2ph-")).sendKeys("Sadhvi");                                   
  //closing the driver         driver.quit();                         }   }


Referenced Console error below:

How to handle this error? Well, Selenium considers this as a compound class, which means more than one classes marked through spaces. So, any class name with spaces in it will be considered two or three or more classes.

In this case, this class name marked as ‘inputtext _58mg _5dba _2ph-‘ contains three spaces thereby making it three different classes. Hence, Selenium mentions the error stating it cannot find multiple classes together. In this case, you can opt to locate element by CSS selector in Selenium or by XPath in Selenium using the class name attribute. The referenced code snippet below:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClassNameLocator {
    public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub                  
  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");         
  WebDriver driver=new ChromeDriver();         
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);                  
  driver.manage().window().maximize();                  //Opening the facebook home page         
  driver.get("https://www.facebook.com/");                  //Locating by firstname via class name         
  driver.findElement(By.xpath("//input[@class='inputtext _58mg _5dba _2ph-']")).sendKeys("Sadhvi");                                   
  //closing the driver         driver.quit();                         
}   
}

How to Locate an Element When We Have Multiple Elements Sharing the Same Class Name

Now, you know when to use the class name and when you cannot use class names. But did you ever imagine the scenario when you have multiple elements sharing the same class name? How do you tackle that situation? This is, again, something you can simply achieve by using the findElements keyword. All you need to do is locate all of the elements with that class name using the findElements keyword and iterate through the required element class name via index. Having said so, I would rather suggest looking into an alternative method of locating that element rather than this, as its tendency of breaking will be pretty high and may lead to errors.

Example for Class Name Locator in Selenium for Multiple Elements With a Similar Class Name

Let’s consider the below example and how it highlights the scenario above. In this case, we are considering the LinkedIn sign-up page, where all fields share the same class name. In this case, we need to note two important things:

  • If no, the index is defined; then, by default, Selenium selects the first element it encounters with that class name. In the code snippet below, it locates the first element, which is the first name:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClassNameLocator {
    public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub                  
  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");         
  WebDriver driver=new ChromeDriver();         
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);                  
  driver.manage().window().maximize();                  //Opening the linkedin sign up home page         
  driver.get("https://www.linkedin.com/start/join");                  //Locating by firstname via class name         
  driver.findElement(By.className("cell-body-textinput")).sendKeys("Sadhvi"); //closing the driver         
  driver.quit();                         
}   }


Note: Take a look at the class name, which, in this case, is cell-body-textinput, since it is not marked with spaces hence it is considered as a single class.

  • Locating the different elements with the same class name using index. The referenced snippet below:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClassNameLocator {
    public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub                  

  System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");         
  WebDriver driver=new ChromeDriver();         
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);                  
  driver.manage().window().maximize();                  //Opening the air bnb home page         
  driver.get("https://www.linkedin.com/start/join");                  //Locating by firstname via class name         
  List<webelement> signUpForm=driver.findElements(By.className("cell-body-textinput"));     
  //finding the number of elments with the same class name         int size=signUpForm.size();                  
  System.out.print(size);                  //locating the first name locator         
  signUpForm.get(0).sendKeys("Sadhvi");                  //locating the last name locator         
  signUpForm.get(1).sendKeys("Singh");             //locating the email  locator         
  signUpForm.get(2).sendKeys("sadhvisingh24@gmail.com");                  //locating the password  locator         
  signUpForm.get(3).sendKeys("password");                                   //closing the driver         
  //driver.quit();                         
}   }   
</webelement>


Console output:

console output

Bingo, you are good to go now! This was all about class name locator in Selenium.

What Did We Learn About Class Name Locator in Selenium?

Well, that was all for today’s Selenium Java tutorial for CSS locator in Selenium. I am sure, by far, you have developed a deep understanding of how to use the Class name locator in Selenium effectively. We came across the most common error across the implementation of Class name locator in Selenium. We also learned how to overcome complicated scenarios where multiple elements are sharing a similar class name.

Adios, and happy testing! 

Java (programming language) Element

Published at DZone with permission of Sadhvi Singh. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Linked List Popular Problems Vol. 1
  • Java: Why a Set Can Contain Duplicate Elements
  • What Is Ant, Really?
  • DataWeave Interview Question: Concatenate Elements of an Array

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!