Open In App

Selenium Locators - Locating By CSS Selectors

Last Updated : 28 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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
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:

  1. Java Development Kit (JDK) installed on your system to compile and run Java applications.
  2. Selenium WebDriver added to your project dependencies, which allows you to interact with web elements and automate browsers.
  3. 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:

output-of-GoogleSearchByCssSelectorTestDemo-
CSS Locators Output

CSS 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.


Article Tags :

Similar Reads