In Selenium automation, CSS selectors are among the most powerful and flexible tools for locating web elements. They are especially useful when dealing with complex or dynamically changing HTML structures. In fact, around 75% of automation testers prefer CSS selectors over other locator strategies due to their speed, readability, and precision. In this article, we’ll break down the different types of CSS selectors available in Selenium using Java and walk you through practical examples to help you implement them effectively in your test scripts.
What is a CSS Selector?
A CSS Selector is a pattern used to select and style elements within an HTML document. In the context of Selenium, CSS selectors allow you to locate elements on a webpage for automation. CSS selectors are generally faster than other locators like XPath and can be more concise, making them a preferred choice for many automation testers. However, their reliability can depend on the specific context and the complexity of the HTML structure.
1. ID Selector
The ID Selector is one of the most straightforward and commonly used CSS selectors. It selects an element based on its unique ID attribute. Since IDs are unique within a webpage, this selector is highly reliable.
Syntax:
WebElement element = driver.findElement(By.cssSelector("#elementID"));
Example:
ID css SelectorWebElement loginButton = driver.findElement(By.cssSelector("#loginBtn"));
loginButton.click();
In this example, the CSS selector #loginBtn
targets the element with the ID loginBtn
.
2. Class Selector
The Class Selector is used to select elements based on their class attribute. Unlike IDs, classes are designed to be reusable across multiple elements, so a class selector can target multiple elements.
Syntax:
WebElement element = driver.findElement(By.cssSelector(".className"));
Example:
Class css SelectorWebElement menuOption = driver.findElement(By.cssSelector(".menu-item"));
menuOption.click();
Here, the selector .menu-item
selects any element with the class menu-item
.
3. Attribute Selector
The Attribute Selector allows you to target elements based on the presence or value of their attributes. This selector is particularly useful when you need to be more specific than just using an ID or class.
Syntax:
WebElement element = driver.findElement(By.cssSelector("[attribute='value']"));
Example:
Attribute css SelectorWebElement emailField = driver.findElement(By.cssSelector("input[type='email']"));
emailField.sendKeys("[email protected]");
This example selects an input element where the type attribute equals email.
4. Combining Attributes
Sometimes, you need to combine multiple attributes to pinpoint an element accurately. Combining attributes in CSS selectors gives you the flexibility to be as specific as needed.
Syntax:
WebElement element = driver.findElement(By.cssSelector("tagName[attribute='value'][attribute2='value2']"));
Example:
Attribute combiner
WebElement submitButton = driver.findElement(By.cssSelector("button[type='submit'][name='login']"));
submitButton.click();
In this case, the selector targets a button element that has both type='submit' and name='login' attributes.
5. Substring Selector
Substring Selectors are advanced CSS selectors that allow you to match elements based on partial attribute values. This is particularly useful when dealing with dynamic attributes.
Substring Selector
Syntax:
WebElement element = driver.findElement(By.cssSelector("tagName[attribute^='startValue']"));
WebElement element = driver.findElement(By.cssSelector("tagName[attribute$='endValue']"));
WebElement element = driver.findElement(By.cssSelector("tagName[attribute*='subString']"));
Example:
WebElement partLink = driver.findElement(By.cssSelector("a[href*='partial-link']"));
partLink.click();
Here, the selector targets an a
tag (anchor) whose href
attribute contains the substring partial-link
. The ^=
operator selects elements where the attribute value starts with the specified substring, $=
selects elements where the attribute value ends with the substring, and *=
selects elements where the attribute value contains the substring.
Conclusion
CSS selectors are an essential tool for identifying and interacting with web elements in Selenium automation. By mastering these selectors, you can write more efficient and reliable test scripts. Whether you're dealing with simple IDs or complex combinations of attributes, CSS selectors provide the precision you need for effective automation.
Explore these examples in your projects to get hands-on experience, and you'll quickly see the power and flexibility of CSS selectors in Selenium WebDriver.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read