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.
findElement by cssSelector in 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.
<button> element with class submit-btn.WebElement button = driver.findElement(By.cssSelector("button.submit-btn"));username.WebElement input = driver.findElement(By.cssSelector("#username"));
<a> link with the exact href attribute.WebElement link = driver.findElement(By.cssSelector("a[href='https://example.com']"));<li> inside a ul inside a div with class container.WebElement item = driver.findElement(By.cssSelector("div.container > ul > li:first-child"));This program opens a browser, goes to example.com, finds the first <h1> element, prints its text, then closes the browser.
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(); } } }
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.
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.
Practice
driver.findElement(By.cssSelector(".btn-primary")) do in Selenium Java?Solution
Step 1: Understand the method used
findElementreturns the first matching element found on the page.Step 2: Analyze the CSS selector
The selector.btn-primarymatches elements with classbtn-primary.Final Answer:
Finds the first element with class 'btn-primary' on the page -> Option BQuick Check:
findElement + .class = first matching element [OK]
- Confusing findElement with findElements
- Using id selector syntax for class
- Thinking it finds all matching elements
Solution
Step 1: Identify CSS selector for id
In CSS, id selectors start with#, so#loginselects element with id 'login'.Step 2: Check syntax correctness
The syntaxdriver.findElement(By.cssSelector("#login"));is correct for Selenium Java.Final Answer:
driver.findElement(By.cssSelector("#login")); -> Option DQuick Check:
Id selector uses # [OK]
- Using . instead of # for id
- Missing quotes around selector
- Using invalid selector syntax
WebElement element = driver.findElement(By.cssSelector("div.content > p.highlight"));
String text = element.getText();
System.out.println(text);Assuming the HTML is:
<div class="content"> <p class="highlight">Hello</p> <p>World</p> </div>
Solution
Step 1: Understand the CSS selector used
div.content > p.highlightselects apelement with classhighlightthat is a direct child ofdivwith classcontent.Step 2: Match selector to HTML
The firstpinsidediv.contenthas classhighlightand text "Hello".Final Answer:
Hello -> Option CQuick Check:
Selector matches first p.highlight text [OK]
- Ignoring direct child combinator >
- Selecting wrong paragraph text
- Assuming all p tags are selected
WebElement button = driver.findElement(By.cssSelector("button#submit-btn.active"));
button.click();Given the HTML:
<button id="submit-btn">Submit</button>
Solution
Step 1: Analyze the CSS selector
The selectorbutton#submit-btn.activelooks for abuttonwith idsubmit-btnAND classactive.Step 2: Compare with HTML element
The button has idsubmit-btnbut no classactive, so selector matches no element.Final Answer:
CSS selector requires both id and class but element has no class 'active' -> Option AQuick Check:
Selector requires all parts to match [OK]
- Assuming partial match works in CSS selector
- Ignoring missing class in element
- Thinking click() method is invalid
input element inside a form with class 'search' that is enabled and visible. Which CSS selector is best to use with findElement in Selenium Java?Solution
Step 1: Understand CSS selectors for enabled inputs
CSS does not have a standard:enabledpseudo-class for all browsers; instead,:not([disabled])selects inputs without the disabled attribute.Step 2: Check options for correctness
form.search input:enabled uses:enabledwhich is not widely supported in CSS selectors for Selenium.
form.search > input[disabled='false'] uses attribute[disabled='false']which is invalid because disabled is boolean attribute.
form.search input:not([disabled]) uses:not([disabled])which correctly selects enabled inputs.
form.search input[visible='true'] uses[visible='true']which is not a valid attribute for visibility.Final Answer:
form.search input:not([disabled]) -> Option AQuick Check:
Use :not([disabled]) to find enabled inputs [OK]
- Using unsupported :enabled pseudo-class
- Checking disabled='false' attribute incorrectly
- Using non-existent visible attribute
Ready to prove it?
Pass the test and this pattern moves unknown
