Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a CSS Selector in Selenium? 
3.
What are locators in Selenium WebDriver?
3.1.
Types of Locators in Selenium WebDriver
4.
Anatomy of a CSS Selector
5.
CSS Selector Examples
6.
Example
7.
Frequently Asked Questions
7.1.
What is CSS selector locator in Selenium?
7.2.
How to find CSS selector in Selenium?
7.3.
What is CSS element selector?
7.4.
Why is CSS helpful?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

CSS Selector in Selenium

Author Shiva
0 upvote

Introduction

CSS Selectors in Selenium provide a robust mechanism for identifying web elements through a strategic blend of HTML tags, ids, classes, and attributes. Learning how to use CSS Selectors makes it simpler to write scripts that work well and do what you want when testing websites.

CSS Selector in Selenium

In this article, we'll go through everything step-by-step to understand CSS Selector in Selenium.

What is a CSS Selector in Selenium? 

In Selenium, a CSS Selector is a pattern used to select and locate HTML elements on a web page. CSS Selectors are employed by the Selenium WebDriver to identify and interact with elements during test automation. They are based on CSS (Cascading Style Sheets) syntax and can target elements by their attributes, types, classes, IDs, and relationships with other elements. CSS Selectors offer a concise and powerful way to specify which elements to interact with during automated testing with Selenium.

What are locators in Selenium WebDriver?

In Selenium WebDriver, locators are mechanisms used to locate and identify web elements on a web page. Locators are crucial for interacting with these elements during test automation. 

Types of Locators in Selenium WebDriver

There are several types of Locators in Selenium WebDriver:

  1. ID Locator: Locates elements by their HTML id attribute, which should be unique on the page.
  2. Name Locator: Finds elements based on their name attribute.
  3. Class Name Locator: Locates elements using their CSS class attribute.
  4. Tag Name Locator: Finds elements by their HTML tag name.
  5. Link Text Locator: Locates hyperlinks by their exact text.
  6. Partial Link Text Locator: Finds hyperlinks by matching a partial text.
  7. XPath Locator: Utilizes XPath expressions to navigate through XML documents. It can be used to locate any element on the web page.
  8. CSS Selector Locator: Selects elements based on CSS selectors, offering a powerful way to identify elements.

Anatomy of a CSS Selector

Let's break down the anatomy of a CSS Selector:

  • Element Name: The element name is the type of HTML element you want to select, like div, a, input, h1, etc.
     
  • ID Selector: The ID selector uniquely identifies an element based on its id attribute. It's represented by a # followed by the ID value.
     
  • Class Selector: The class selector identifies elements based on their class attribute. It's represented by a . followed by the class name.
     
  • Attribute Selector: The attribute selector allows you to select elements based on any attribute, not just ID or class. For example, you can select all elements with a specific attribute value.
     
  • Descendant Selector: The descendant selector is used to select elements that are descendants of another element. It's represented by a space between two or more selectors.
     
  • Child Selector: The child selector is similar to the descendant selector but only selects elements that are direct children of another element. It's represented by > between two selectors.

CSS Selector Examples

Now, let's see some examples of CSS Selectors to understand them better:

1. Selecting by Element Name:

  • div: Selects all <div> elements on the page.
  • p: Selects all <p> elements on the page.
     

2. Selecting by ID:

  • #header: Select the element with id="header".
     

3. Selecting by Class:

  • .button: Selects all elements with class="button".
  • .navbar li: Selects all <li> elements that are descendants of an element with class="navbar".
     

4. Selecting by Attribute:

  • [type="text"]: Selects all elements with type="text".
  • [data-testid="submit-button"]: Selects an element with data-testid="submit-button" attribute.
     

Example

For this, Let’s quickly set up our node project. Let us create a test script that navigates to Google's homepage and performs a search using a CSS selector for the term "Coding Ninja". With the help of the CSS selector, we will locate the search input element. So let us get started.

 

Step 1: Initialize node package manager

npm init


Step 2: Install packages using command 

npm i –save selenium-webdriver chromedriver

In the selenium-webdriver package, you'll find several classes and methods that let you launch a browser, go to URLs, find elements on a web page, interact with those elements (by clicking, typing, etc.), and more.

The Chrome WebDriver executable (chromedriver) needed to automate Google Chrome with Selenium is referred to by the term "chromedriver package," which is not an actual npm package. Similarly, you need geckodriver for Firefox, msedgedriver for Edge.

selenium-webdriver package

Step 3: Make a test file named google_search_test.js inside the tests folder. Then, write the following code:

const {
	By,
	Key,
	Builder
} = require('selenium-webdriver');
require('chromedriver')
async function test_case() {
	let driver = await new Builder().forBrowser('chrome').build();
	await driver.get('https://google.com')
	await driver.findElement(By.css('input[name="q"]')).sendKeys("Coding Ninja", Key.RETURN)
	setInterval(function() {
		driver.quit()
	}, 20000)
}
test_case();

 

Step 4: Execute the code using the command: 

node .\google_search_test.js

google_search_test.js

When we execute the test script using the command node .\google_search_test.js, the program launches Google Chrome. Then it navigates to the search page, input the search query "Coding Ninja" using a CSS selector. Then automatically close the browser after a 20-second wait.

Frequently Asked Questions

What is CSS selector locator in Selenium?

CSS selector locator in Selenium is a pattern that selects HTML elements for automation using CSS syntax, offering a powerful way to identify and interact with elements.

How to find CSS selector in Selenium?

To find CSS selector in Selenium you can use browser developer tools or browser extensions to inspect elements and obtain their CSS selectors. Alternatively, construct CSS selectors based on element attributes and relationships.

What is CSS element selector?

A CSS element selector targets specific HTML elements based on their tag names, allowing precise styling and selection in web development and automation.

Why is CSS helpful?

CSS is beneficial for styling web pages, and in automation, CSS selectors provide a concise and robust way to locate and interact with elements during Selenium testing.

Conclusion

You now understand how to interact with web items using CSS Selector in Selenium. Remember that web automation is a valuable ability to help you with your testing and development duties by saving you time and effort.

Recommended Readings:


You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Live masterclass