How to Locate Elements Using By.cssSelector() in Selenium WebDriver
CSS Selector is one of the most powerful and flexible locators provided by Selenium. It allows you to target elements using CSS syntax — the same way you would in stylesheets.
🔎 What is a CSS Selector?
A CSS Selector is a string pattern used to select elements based on their attributes, hierarchy, ID, class, or other characteristics. It is fast and widely used in both testing and frontend development.
<input type="email" id="userEmail" class="input-field login-input" name="email" />
✅ When to Use By.cssSelector()?
- ✅ When elements have multiple attributes
- ✅ When you need to use hierarchical or parent-child selection
- ✅ When elements don’t have unique IDs or names
📌 Syntax in Java
driver.findElement(By.cssSelector("css_selector_expression"));
💡 Common CSS Selector Patterns
tagname[attribute='value']– Attribute selector#id– Select element by ID.class– Select element by classdiv.class input[type='text']– Parent-child selectioninput[name^='user']– Starts with attributeinput[name$='Email']– Ends with attribute
💻 Selenium + Java Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LoginUsingCssSelector {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
// Locate elements using CSS Selector
WebElement emailField = driver.findElement(By.cssSelector("input#userEmail"));
WebElement passwordField = driver.findElement(By.cssSelector("input[name='password']"));
WebElement loginButton = driver.findElement(By.cssSelector("button.login-btn"));
emailField.sendKeys("test@example.com");
passwordField.sendKeys("password123");
loginButton.click();
driver.quit();
}
}
✅ Best Practices
| Tip | Why? |
|---|---|
| Use specific selectors | To avoid selecting unintended elements |
| Avoid overly complex selectors | To keep tests maintainable and readable |
| Combine attributes | To increase accuracy when IDs/classes are reused |
⚠️ Common Mistakes
| Mistake | Fix |
|---|---|
| Using space instead of dot in class | .login-btn not login btn |
| Using # with class | Use #id and .class properly |
| Multiple elements matched | Use findElements() if needed |
🧪 Example: Selecting by Partial Attribute
// Starts-with attribute
WebElement input1 = driver.findElement(By.cssSelector("input[name^='user']"));
// Ends-with attribute
WebElement input2 = driver.findElement(By.cssSelector("input[name$='Email']"));
📚 Summary
By.cssSelector()is a flexible, efficient way to locate elements in Selenium.- Supports attribute, class, ID, and complex structure selection.
- Often preferred over XPath for simplicity and speed.
🚀 What’s Next?
Continue learning other Selenium locators: