0
0
Selenium Javatesting~5 mins

findElement by cssSelector in Selenium Java

Choose your learning style9 modes available
Introduction

We use findElement with cssSelector to quickly find a web page element using CSS rules, just like how you pick a specific item from a shelf by its label.

When you want to click a button identified by its CSS class.
When you need to enter text into a text box with a unique CSS ID.
When you want to check if a specific element with a certain style exists on the page.
When XPath is too complex and CSS selectors offer a simpler way to find elements.
When you want to find elements based on their relationship in the HTML structure using CSS selectors.
Syntax
Selenium Java
WebElement element = driver.findElement(By.cssSelector("css_selector_here"));

The cssSelector string uses standard CSS syntax to locate elements.

findElement returns the first matching element or throws an exception if none found.

Examples
Finds the first <button> element with class submit-btn.
Selenium Java
WebElement button = driver.findElement(By.cssSelector("button.submit-btn"));
Finds the element with ID username.
Selenium Java
WebElement input = driver.findElement(By.cssSelector("#username"));
Finds the first <a> link with the exact href attribute.
Selenium Java
WebElement link = driver.findElement(By.cssSelector("a[href='https://example.com']"));
Finds the first <li> inside a ul inside a div with class container.
Selenium Java
WebElement item = driver.findElement(By.cssSelector("div.container > ul > li:first-child"));
Sample Program

This program opens a browser, goes to example.com, finds the first <h1> element, prints its text, then closes the browser.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CssSelectorExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");
            WebElement heading = driver.findElement(By.cssSelector("h1"));
            String text = heading.getText();
            System.out.println("Heading text: " + text);
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

If no element matches the CSS selector, findElement throws NoSuchElementException.

Use browser DevTools to test CSS selectors before using them in code.

CSS selectors are usually faster than XPath in Selenium.

Summary

findElement by cssSelector helps locate web elements using CSS rules.

It returns the first matching element or throws an error if none found.

Use simple CSS selectors for faster and clearer element finding.