- CSS Selector in Selenium: Locate Elements with Examples
- What is a CSS Selector?
- Types of CSS Selectors (with Examples)
- 1. ID
- 2. Class
- 3. Attribute
- 4. Sub-string
- 5. Inner text
- Selenium CSS Selectors Examples
- CSS Selectors by Attribute
- Id Attribute
- Class Attribute
- Multiple Attributes
- Attribute NOT contain a specific value
- Locating Child Element
- Multiple Child Elements
- Dynamically Generated Ids
- Attribute Starts with
- Attribute Ends with
- Attribute Contains
- How to Use CSS Selector in Selenium WebDriver | 13 Examples
- CSS Selectors by Attribute
- CSS Selector Tag and ID Attribute
- CSS Selector Class Attribute
- Handling Multiple Classes or Space Character in Class Name
- Locate Elements with Sub-strings or Partial Match
CSS Selector in Selenium: Locate Elements with Examples
This article will discuss and describe, with examples, how one can use CSS selectors in Selenium test scripts to identify web elements. It will also depict CSS selectors’ syntax in Selenium.
It is recommended to gain a deeper understanding of locators in Selenium before narrowing it down to CSS selectors in particular.
What is a CSS Selector?
The CSS Selector combines an element selector and a selector value that can identify particular elements on a web page. Like XPath in Selenium, CSS selectors can locate web elements without ID, class, or Name.
Types of CSS Selectors (with Examples)
There are five types of CSS Selectors in Selenium tests:
1. ID
In this example, the script will access the Email text box on the login form at Gmail.com.
The text box carries an ID attribute with the value “Email”. In this case, the ID attribute and its value are utilized to create a CSS selector that allows access to the text box.
How to create the Selenium CSS Selector for the web element
Locate the web element – Email textbox. The HTML tag here is “input” and the ID attribute’s value is “Email”. Combined, they refer to the Email textbox. This is the data required to create the CSS selector.
Verify locator value
Type “css=input#Email”(locator value) in Selenium IDE. Click on the Find button. The Email text box is highlighted, verifying the locator value.
- HTML tag: used to denote the web element to be accessed
- #: used to symbolize the ID attribute. Note that the hash is mandatory in cases where ID attribute is used to create a CSS Selector.
- Value of ID attribute: the value of the ID attribute being accessed. The hash always precedes this value.
When specifying CSS Selector in the target text box of Selenium IDE, ensure that it is preceded by “css=”.
Note: The first element marked in the page source will be identified if multiple web elements have the same HTML tag and attribute value.
2. Class
In this example, the script will access the “Stay signed in” checkbox that appears below the login form at Gmail.com.
The checkbox carries a Class attribute with the value “remember”. This Class attribute and value can be utilized to create a CSS selector that accesses the selected web element.
Here’s how to create a CSS Selector for the web element
Locate the web element – “Stay signed in” checkbox. The HTML tag, in this case, is “label” and the ID attribute’s value is “remember”. Combined, they refer to the “Stay signed in” checkbox.
Verify locator value
Type “css=label.remember”(locator value) in Selenium IDE. Click on the Find Button. The “Stay signed in” checkbox is highlighted, verifying the locator value.
- . : The dot is used to symbolize the Class attribute. Note that the dot is mandatory in cases where a Class attribute is used to create a CSS Selector. A dot always precedes the value of the Class.
3. Attribute
In this example, the script will access the “Sign in” button located beneath the login form at Gmail.com.
The “Sign in” button carries a type attribute with the value “submit”. This attribute and its value can be utilized to create a CSS Selector that will access the preferred web element.
Here’s how to create a CSS Selector in Selenium for the Web Element
Locate the web element – “Sign in” button. The HTML tag, in this case, is “input”, the attribute is the type, and the attribute’s value is “submit”. Combined, they refer to the “Sign in” button.
Verify locator value
Type “css=input[type=’submit’]” (locator value) in Selenium IDE. Click on the Find Button. The “Sign in” button will be highlighted, verifying the locator value.
- Attribute: Used to create the CSS Selector. It can be a value, type, name, etc. It is best to select an attribute with a value that uniquely identifies the accessed web element.
- Value of attribute: the value of the attribute that is being accessed.
4. Sub-string
In Selenium, CSS allows the matching of a partial string which offers a way to create CSS selectors utilizing sub-strings. This can be done in three ways.
Types of mechanisms used to match sub-strings
Match a prefix
This purpose is to correspond to the string by using a matching prefix.
- ^ : the symbol used to match a string using a prefix
- Prefix: the string based on which the match operation is performed.
If one intends to identify the “Password textbox”, the CSS Selector, in this case, would be:
Match a suffix
This purpose is to correspond to the string by using a matching suffix.
- #: the symbol used to match a string using a suffix.
- Suffix: the string based on which the match operation is performed.
Again, if one intends to identify the “Password textbox”, the CSS Selector, in this case, would be:
Match a substring
This purpose is to correspond to the string by using a matching substring.
- *: the symbol to match a string using sub-string
- Sub string: the string based on which the match operation is performed.
Again, if one intends to identify the “Password textbox”, the corresponding CSS Selector would be:
5. Inner text
Using inner text helps identify and create CSS Selectors in Selenium WebDriver by utilizing a string pattern that the HTML Tag manifests on the web page. This mechanism is used most frequently to locate web elements because of its simplified syntax.
In this example, focus on the “Forgot email?” hyperlink present beneath the login form at Gmail.com.
The anchor tag that represents this hyperlink has some text within it. This text can create a CSS Selector that locates the required web element.
- : – the colon is used to symbolize the contains method
- contains – the value of the Class attribute that is being accessed
Update:The feature is deprecated and no longer supported by the W3C standard. CSS Selectors Level 3 standard is applicable across all major browsers. - text – the text displayed anywhere on the web page, irrespective of its location
It is helpful to find an element by CSS selectors, mainly because advanced developers and testers use it. By mastering it, one can use Selenium to its full potential, thus optimizing its abilities for automated Selenium testing.
Selenium CSS Selectors Examples
Last updated: 19 March 2020 Locating elements by CSS selectors is the preferred way as it is faster and more readable than XPath. This tutorial provides examples of how to locate web elements in Selenium using CSS selectors.
CSS Selectors by Attribute
WebElement firstName = driver.findElement(By.cssSelector("input[name='first_name']"));
Id Attribute
driver.findElement(By.cssSelector("input#firstname")); //or driver.findElement(By.cssSelector("#firstname"));
Class Attribute
driver.findElement(By.cssSelector("input.myForm")); //or driver.findElement(By.cssSelector(".myForm"));
Note: Take extra care when using the . notation as there could be many web elements on the HTML source with the same class attribute.
Multiple Attributes
Sometimes there is a need to be more specific with the selection criteria in order to locate the correct element.
The value of the display could either be “none” or “block” depending on the ajax call. In this situation, we have to locate the element by both class and style. Example:
driver.findElement(By.cssSelector("div[class='ajax_enabled'] [style='display:block']"));
Attribute NOT contain a specific value
In WebDriver, how do you find elements whose attribute contain values which you don’t want to select? This CSS selector example shows how NOT to select by specific attribute value Suppose you have many elements which share the same attribute and attribute value, but some of those elements have other variables appended to the value. e.g:
In the above snippet, we want to select an available day (i.e. the two last div elements) As can be seen, all four divs contain “calendar-day-“ but the first two also contain “unavailable” which we don’t want. The CSS selector for Not selecting the first two divs is
driver.findElement(By.cssSelector("div[class*=calendar-day-]:not([class*='unavailable'])"));"
Locating Child Element
driver.findElement(By.cssSelector("div#logo img"));
Multiple Child Elements
There are occasions when there are multiple child elements within the same parent element such as list elements
As can be seen, the individual list elements don’t have any id associated with them. To locate the element with text ‘Orange’, we have to use nth-of-type . Example:
driver.findElement(By.cssSelector("ul#fruit li:nth-of-type(2)"));
driver.findElement(By.cssSelector("ul#fruit li:last-child"));
Dynamically Generated Ids
We can use string matchers to locate elements with dynamically generated Ids. In this example, all the three div elements contain the word ‘random’.
Attribute Starts with
driver.findElement(By.cssSelector("div[id^='123']"));
Attribute Ends with
driver.findElement(By.cssSelector("div[id$='456']"));
Attribute Contains
driver.findElement(By.cssSelector("div[id*='_pattern_']"));
driver.findElement(By.cssSelector("div:contains('_pattern_')"));
How to Use CSS Selector in Selenium WebDriver | 13 Examples
Selenium Webdriver is very powerful to automate web applications. We can identify web elements in Selenium Webdriver using various locators and CSS Selector is one of them.CSS Selector in Selenium acts as the best workaround to find an element when we don’t have an option to locate an element using Id or Name. Also, it is faster and simpler than XPath.To know more about XPath please refer exclusive article on Xpath XPath in Selenium WebDriver with Example .In the following examples, we will see how to use CSS Selectors in Selenium.
CSS Selectors by Attribute
Suppose we have an Html tag with the following attributes.
The syntax to locate elements by attribute are as follows
tagName[attributename=’attributeValue’]
Since name might not be a unique property on the web we can combine more than one attribute to find an element uniquely. For that, the syntax is as follows:
CSS Selector Tag and ID Attribute
In CSS, a hash (#) notation refers to the id attribute of an element.
Syntax 1:
Syntax 2:
CSS Selector Class Attribute
A dot (.) notation is used to refer to the class attribute of an element.
Handling Multiple Classes or Space Character in Class Name
Suppose we have an Html tag with the following attributes.
In the above HTML tag, three classes (abc, pqr, and xyz) are being used for the single text. box. You can not write a statement like By.cssSelector(“.abc pqr xyz”) to identify an element.If you write such code Selenium will throw NoSuchElementException error. Developers can use such class having multiple class names for different elements on the page. Out of all the class names, a few of the names might be unique. To handle such a scenario we have to join the classes using a dot(.) notation unless the required element is identified uniquely. The following are the possible ways to refer to the element.
Locate Elements with Sub-strings or Partial Match
Using CSS locators, we can also locate elements with some matching patterns or sub-strings. It becomes very helpful to identify elements with dynamically generated ids. This is achieved by using three special characters ^, $, and *.
‘^’ symbol, represents the starting text in a string.
‘$’ symbol represents the ending text in a string.
‘*’ symbol represents contains text in a string.
Let’s consider a web page has the following HTML Tags