Selenium Locators - Locating By CSS Selectors
Last Updated :
28 Jul, 2025
In Selenium WebDriver, one of the most versatile and powerful ways to locate elements is by using CSS Selectors. The By.cssSelector strategy allows you to select elements using CSS syntax, providing flexibility in selecting elements based on various attributes like ID, class, type, name, or even hierarchical relationships between elements.
Here are the steps for using the CSS Selector locator strategy in Selenium with Java:
Syntax:
For example, consider this HTML input element:
Google css Selector Inspect page<input type="text" id="search" name="q" class="gLFyf" placeholder="Search Google">
You can locate this element using a CSS Selector like input[name='q'], CSS Selectors are highly versatile, allowing you to find elements with precision, even in complex web pages.
input[name='q']
: Targets an input
element with the name attribute equal to "q".input#gLFyf
: Targets an input
element with the class "gLFyf".input#search
: Targets the input element with the id
attribute equal to "search".
Steps for Locating Strategies by CSS Selector Locator
Here are the steps of locating strategies By.cssSelector:
Step 1: Set up Your Project
To get started with Selenium WebDriver, make sure you have the following setup:
- Java Development Kit (JDK) installed on your system to compile and run Java applications.
- Selenium WebDriver added to your project dependencies, which allows you to interact with web elements and automate browsers.
- Maven or Gradle for managing your project's dependencies, including Selenium WebDriver, to ensure easy and efficient integration.
If using Maven, your pom.xml
should include the following dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
Step 2: Sample Code for Google Search Using CSS Selector
Java
package Tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GoogleSearchByCssSelectorTestDemo {
public static void main(String[] args) {
// Use a StringBuilder to collect all output messages
StringBuilder outputMessages = new StringBuilder();
// Step 1: Set the path to Chromedriver manually
// Replace this with the path where you downloaded chromedriver.exe
System.setProperty("webdriver.chrome.driver", "C:/path-of-the-webdriver/chromedriver.exe"); // Update this path
outputMessages.append("Setting up Chrome WebDriver...\n");
// Step 2: Initialize ChromeDriver
WebDriver driver = new ChromeDriver();
outputMessages.append("ChromeDriver initialized. Browser opened.\n");
try {
// Step 3: Navigate to Google.com
outputMessages.append("Navigating to Google.com...\n");
driver.get("https://www.google.com/");
outputMessages.append("Landed on: ").append(driver.getCurrentUrl()).append("\n");
// Step 4: Locate search box using CSS Selector
outputMessages.append("Finding search box with CSS Selector 'input[name=\"q\"]'...\n");
WebElement searchBox = driver.findElement(By.cssSelector("input[name='q']"));
outputMessages.append("Search box found.\n");
// Step 5: Enter search query
outputMessages.append("Entering 'Selenium WebDriver' into search box...\n");
searchBox.sendKeys("Selenium WebDriver");
outputMessages.append("Search query entered.\n");
// Step 6: Submit search
outputMessages.append("Submitting search...\n");
searchBox.submit();
outputMessages.append("Search submitted.\n");
// Step 7: Print page title
String pageTitle = driver.getTitle();
outputMessages.append("Results Page Title: ").append(pageTitle).append("\n");
} catch (Exception e) {
outputMessages.append("!!! Test failed with error: ").append(e.getMessage()).append("\n");
// For debugging, you might still want to print stack trace immediately or log to a file
e.printStackTrace();
} finally {
// Step 8: Close browser
outputMessages.append("Shutting down browser...\n");
if (driver != null) {
driver.quit();
outputMessages.append("Browser closed.\n");
}
outputMessages.append("Test complete.\n");
// Print all collected messages at the very end
System.out.println("\n--- TEST EXECUTION SUMMARY ---\n" + outputMessages.toString());
}
}
}
Output:
CSS Locators OutputCSS Selector in Selenium is a powerful and versatile tool for automating web interactions. It allows you to locate elements using patterns based on their attributes, classes, or relationships in the DOM structure. Its flexibility makes it ideal for tasks like filling out search boxes, clicking buttons, or navigating complex web page layouts.
CSS selectors are not only fast but also precise, enabling testers to interact with elements more efficiently.
Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING