In Selenium, CSS selectors are one of the most powerful and flexible ways to identify web elements on a page. Whether you're dealing with complex HTML structures or need to target specific elements, understanding CSS selectors is crucial for effective test automation. In this article, we'll explore the various types of CSS selectors in Selenium using Java and provide examples to help you implement them in your automation 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 Selector
WebElement 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
CSS Selectors
CSS selectors are used to target HTML elements on your pages, allowing you to apply styles based on their ID, class, type attributes, and more. There are mainly 5 types of selectors.Basic CSS Selectors: These are used to target elements by tag, .class, or #id for fundamental styling needs.Combinator
7 min read
CSS ::selection Selector
The ::selection CSS pseudo-element allows you to style the part of a webpage that users highlight, such as when they drag the mouse over text. Itâs a simple way for developers to customize the appearance of selected text, improving the overall user experience. However, only a few CSS properties can
2 min read
CSS * (Universal) Selector
The universal selector (*) applies styles to all elements on a page or within a specified context, regardless of their type, class, or ID. It's commonly used for global resets or universal styling. * { /* styles */}1. Basic Use case of universal selectorThe universal selector applies styles to all e
4 min read
CSS :target Selector
The target selector is used to represent a unique element (the target element) with an id matching the URL's fragment. It can be used to style the current active target element. URLs with a # followed by an anchor name link to a certain element within a document. The element being linked to is the t
2 min read
Selenium Features
Selenium was created by Jason Huggins, a software engineer at ThoughtWorks, back in 2004. He was working on a web application that needed frequent testing, and to save time and effort, he decided to automate the process. To do this, he built a JavaScript program called "JavaScriptTestRunner," which
6 min read
CSS #id Selector
The ID selector in CSS is used to select a single element on a page by referencing its id attribute. This attribute must be unique within a page, meaning no two elements can have the same id. The ID selector is prefixed with a hash (#) symbol in CSS. Basic ID SelectorThe ID selector allows you to st
8 min read
CSS element Selector
The element selector in CSS is used to select HTML elements that are required to be styled. In a selector declaration, there is the name of the HTML element and the CSS properties which are to be applied to that element is written inside the brackets {}. Syntax: element { \\ CSS property}Example 1:
2 min read
CSS :read-write Selector
The :read-write selector is used to select an element (such as an input text) that is editable by the user. The elements with no readonly and disabled attribute are defined as readable and writable. Syntax: :read-write { // CSS Property}Example 1: [GFGTABS] HTML <!DOCTYPE html> <html>
2 min read
CSS :nth-of-type() Selector
The :nth-of-type() in css Selector is used to style only those elements which are the nth number of child of its parent element. An n may be a number, a keyword, or a formula. Syntax: :nth-of-type(number) { // CSS Property;} Where number is the argument that represents the pattern for matching eleme
2 min read
CSS [attribute=value] Selector
The [attribute=value] selector in CSS is used to select those elements whose attribute value is equal to "value". Syntax: element [attribute = "value"] { // CSS Property}Note: <!DOCTYPE> must be declared for IE8 and earlier versions. Example 1: In this example, The selector h1[id="geeks"] targ
2 min read