How to Locate Web Elements Using CSS Selector in Selenium?

Last updated on Oct 17,2024 28.7K Views

How to Locate Web Elements Using CSS Selector in Selenium?

edureka.co

In Selenium WebDriver, in order to interact with a web element such as a click, or type something, we need to first locate the elements. One of the most important tasks of a test automation engineer is to be able to identify different elements on the webpage. There are several element locators but, locating elements using CSS Selectors is the preferred way as it is faster than XPath.  

I hope you guys must have understood how to locate elements on the web page using XPath and the plugin which helps in locating the XPath, ChroPath which are widely used element locators in Selenium. So, in this article, we’ll see how CSS takes the front line in finding an element. For further details, you can refer to the Selenium Training.

So let’s begin the discussion learning about what are the element locators in Selenium and why is it of such soaring importance.

CSS Selectors: What are element locators? Why is it used?

Locating elements is indeed a nightmare because of the complexity of finding a web element in the webpage and them. To simplify this task, we use something known as locators in Selenium

Locators are defined as an address that identifies a web element uniquely within the webpage. It is basically a command that tells the Selenium IDE which GUI elements like – Text Box, Buttons, Check Boxes, etc. it needs to operate on.

Finding correct GUI elements is considered as a prerequisite for creating an automation script but, accurate identification of GUI elements is much more difficult than it sounds. Sometimes, you might even end up working with incorrect GUI elements or no elements at all! Hence, using the right locator ensures that the tests are faster, more reliable or has lower maintenance.

This helps us understand what Selenium can actually do. Now that you’ve understood what are element locators, let’s dive deeper and understand the various types of locators in Selenium. Learn more about Automation Testing and its applications from the Automation Testing Certification.

CSS Selectors: Different Types of Selenium Locators

There is a distinct range of web elements such as text box, check box, drop down menu, radio button, etc. It requires an effective and accurate approach to identify these elements. Thereby, you can propound that with an increase in the effectiveness of locator, the stability of the automation script will increase.

In order to identify web elements accurately and precisely, Selenium makes use of different types of locators. They are as follows:

Let’s understand each of them in detail.

  1. ID locator: The most popular way to identify web element is to use ID. ID’s are considered as the safest and fastest locator option and should always be the first priority among the multiple locators.
  2. Name locator: This is also an effective way to locate an element which has a name attribute. With this strategy, the first element with the value of the name attribute will be returned. If no element has a matching name attribute, then a  NoSuchElementException will be raised.
  3. LinkText & ParialLinkText: You can identify the hyperlinks on a web page using this linkText. It can be determined with the help of an anchor tag (<a>). In order to create the hyperlinks on a web page, you can use the anchor tags followed by the link text. In some cases, you may need to find links by a portion of the text in a linkText element. In such situations, you can use Partial Link Text to locate elements.
  4. CSS Selectors: CSS is mainly used to provide style rules for the web pages and you can use it for identifying one or more elements in the web page. The CSS selector is always the best possible way to locate complex elements in the page. We’ll talk more about CSS selectors in the next topic. 
  5. XPath: XPath is a language to query XML documents. XPath is an important strategy to locate elements in selenium. It also consists of a path expression along with some conditions. Here, you can easily write an XPath script/query to locate any element in the webpage. 

Also, take a look at this video on different types of element locators in Selenium.

Locators In Selenium Webdriver | Elements Locators In Selenium | Selenium Training

This Edureka video on Locators in Selenium talks about different types of selenium locators and steps involved to locate a web element using locators along with examples.

Having understood this, let’s understand the main concept of this article, What are CSS Selectors in Selenium Webdriver.

CSS Selectors: What are CSS Selectors?

As we know every modern web page is build of CSS, they define the cosmetic behavior (like size, fonts, inclination, etc.) of the whole page and/or objects in the page. The CSS rules do the grouping by class names of objects to define the combined cosmetic behavior of those objects. Similarly, we can use Object’s id property to define the individual object’s look and feel. We can also use CSS properties to identify objects.

This CSS Selector is the combination of an element and a selector value, which identifies the web element within a web page. The composite of an element and selector value is known as the Selector Pattern. This selector pattern is constructed using HTML tags, attributes, and their values. 

Using CSS selectors to locate elements has some benefits:


Now let’s take a look at a few basic commands which help in locating the elements.

CSS Selector: Basic commands

First, let’s take a look at the syntax.

Syntax of CSS Selector

example:

driver.findElement(By.cssSelector("#gh-btn")).click();

If we have the class attribute specified, 

This command helps in finding the element which has a class attribute specified.

Example: 

driver.findElement(By.cssSelector(class.’typeahead__button’)).click();

 

 

Example:

css=input#Passwd[name$=’wd’]

<HTML tag> [ locator  ^ = ‘value’ ]

Example

css=input#Passwd[name^=’Pass’]

<HTML tag> [ locator $ = ‘value’ ]

Example

css=input#Passwd[name$=’wd’]

Example

css=input#Passwd[name:’Pass’]

Having understood this, we’ll move on and take a look at a demo where we’ll learn how CSS Selectors in Selenium Webdriver work.

CSS Selector in Selenium WebDriver | Selenium Tutorial | Selenium Certification Training

This ‘CSS Selector in Selenium’ video by Edureka helps you understand how this locator aids to identify elements on a web page.

CSS Selector: Demo

We’ll perform automation testing on one of the most famous e-commerce websites, i.e. Ebay.com in this demo. Let’s see how this can be done. We will see how to register the drivers for chrome and how to search an element on the page. We’ll consider working on the Eclipse IDE because it is easy to execute Java programs. 

For google chrome, you need to install a chrome driver in your system. Now let’s take a closer look at the code. As you can see,


package co.edureka;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DemoClass {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:UsersVaishnaviDesktopChromechromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://ebay.com");
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.findElement(By.cssSelector("#gh-ac")).sendKeys("OnePlus6T");
driver.findElement(By.cssSelector("#gh-btn")).click();
js.executeScript("window.scrollBy(0,300)");
}

}

This yields the output

First, this will open ebay.com and then we’ll search for OnePlus6T and click on the search icon.

After this, we’ll scroll down the page.

If you wish to learn Selenium and build a career in Selenium Technologies, then check out our Selenium training which comes with instructor-led live training and real-life project experience. This training will help you understand Selenium in-depth and help you achieve mastery over the subject.

Find out our Selenium Training in Top Cities/Countries

IndiaOther Cities/Countries
BangaloreUS
HyderabadUK
PuneCanada
ChennaiAustralia
MumbaiSingapore
KolkataEdinburgh

Now with this, we come to an end to this “CSS Selector in Selenium” blog. I Hope you guys enjoyed this article and understood what role CSS has to play in Selenium. Now that you have understood how to locate an element using the CSS Selector, check out the Selenium Certification Course by Edureka, a trusted online learning company with a network of more than 650,000 satisfied learners spread across the globe. This course is designed to introduce you to the complete Selenium features and its importance in testing software. Got a question for us? Please mention it in the comments section of “CSS Selectors in Selenium” and we will get back to you.

Upcoming Batches For Selenium Course
Course NameDateDetails
Selenium Course

Class Starts on 23rd November,2024

23rd November

SAT&SUN (Weekend Batch)
View Details
Selenium Course

Class Starts on 25th November,2024

25th November

MON-FRI (Weekday Batch)
View Details
Selenium Course

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Selenium Framework Explained in 60 Minutes