CSS Selectors in Selenium: Pro-Tester’s Mastering Guide
Bharadwaj Pendyala
Posted On: February 26, 2019
62286 Views
7 Min Read
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Locators Tutorial.
CSS Selectors in Selenium are used to identifying a user desired HTML web element. This fits into an element locator strategy of automated test development where the primary aim is to interact with page elements through different types of locators. While there are several other methods to identify element locator such as id, name, class name, link text, partial link text, XPath, tag name etc. other than CSS selectors in Selenium we prefer the CSS way due to below benefits.
New to CSS Selectors? Check out this Ultimate CSS Selector cheat sheet to boost your web designing career.
If you’re new to Selenium and wondering what it is then we recommend checking out our guide – What is Selenium?
Why Choose CSS Selectors in Selenium Over Other Element Identifiers?
- Faster Identification and reduced test execution time – Compared to XPath CSS selectors in Selenium would tend to identify the elements better as most used browsers such as Chrome and Firefox are tuned for better performance with CSS selectors in Selenium. Here is the link which provides performance stats for reference.
- Availability of better documentation.
- Enhanced readability.
Different Ways Of Identifying CSS Selectors in Selenium
Let’s discuss the different ways of identifying the CSS Selenium locators of web elements.
Class Selector Conundrum
‘.’ represents a class in CSS and is used to identify web elements with a specific class. For example, if our web element of p is consisting of the class below. The following could be correlated to XPath programming of identifying the class with the tag name [@class = ’value’ ] or it could also be correlated with class name element locator in Selenium.
1 |
<p class=" pages-sub-title"> Lambda Test blog post on validating CSS Selectors in Selenium </p> |
CSS selector in Selenium for the same could be identified with the class name as
“.page-sub-title”
The CSS syntax in Selenium of class selector would be –
<.> < Class Name> (or)
<.>
This certification is for anyone who wants to stay ahead among professionals who are growing their career in Selenium automation testing.
Here’s a short glimpse of the Selenium 101 certification from LambdaTest:
ID Selector Conundrum
‘#’ represents id in CSS and is used to identify web elements with a specific id. Please find an example listed below for matching the web element with ID. If you observe it at a high level this can be compared to that of ID name selector using Selenium methods and also locating the element with id in XPath programming such as tag name [@id = ‘id_value’ ].
1 2 3 |
<li id="menu-item-143" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-143"> <a href="https://www.lambdatest.com/blog/category/lambdatest-updates/">Product Updates</a> </li> |
CSS selector in Selenium for the same could be identified with the class name as
#menu-item-143 or div#menu-item-143
The CSS syntax in Selenium of the ID selector would be –
<#> < ID Name> (or)
<#>
Attribute Selector Conundrum
Attributes could be represented in key-value pairs, for example in the below example we have multiple attributes and values such as ‘role = dialog’, ‘data-dismiss = modal’ etc. Xpath programming version of attribute selector could be correlated as tag name [@attribute key = ‘attribute value’ ].
1 2 3 4 |
<div class="modal fade" id="whitepaper-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <span class="close" data-dismiss="modal" style="top: 4px; position: absolute; right: 10px;"> <span aria-hidden="true">×</span> </span> |
CSS selector in Selenium for the same could be identified with the class name as
div[role=’dialog’] or [role=’dialog’]
‘Class or ID’ & Attribute Selector Conundrum
Class or ID and attribute combination could serve as a better strategy which is more powerful than that of using a class, id or attribute selector alone. In order to achieve uniqueness of the element, if above 3 ways of identifying fails due to multiple instances of the same locator this could be a go-to solution. Let’s deduct the element locator strategy for below example from our LambdaTest blog.
1 |
<nav id="site navigation" class="navigation main-navigation" role="navigation"> |
In the above HTML snippet if you observe there is a space in the class name which is “navigation main-navigation” this could be represented as navigation.main-navigation space can be ignored and replaced with ‘.’
CSS Selector in Selenium for the same could be identified as below:
1 |
nav.navigation.main-navigation[role='navigation'] |
The CSS syntax in Selenium of class or id and attribute selector would be:
1 |
<HTML Tag> <Class Or ID> [ <attribute key> = ‘<attribute value>’ ] |
or
1 |
<Class Or ID> [ <attribute key> = ‘<attribute value>’ ] |
SubString Match Conundrum
In order to enable even powerful querying technique, we can make use of sub-string matches with ^ indicated prefix, $ indicating suffix and * indicating substring. If you observe closely this is similar to the representation of XPath functions such as starts-with, contains and ends with. Let’s get into detailed usage of all the three ways of dealing with matches.
^ Indicating a prefix match
Syntax:
1 |
<HTML Tag> [ <Class Or ID> ^= <Class or ID Name> ] |
Example:
1 |
div[class^=’aria-label’] |
$ Indicating a suffix match
Syntax:
1 |
<HTML Tag> [ <Class Or ID> $= <Class or ID Name> ] |
Example:
1 |
a[class$=’aria-label’] |
* Indicating a substring match
Syntax:
1 |
<HTML Tag> [ <Class Or ID> *= <Class or ID Name> ] |
Example:
1 |
p[class*=’aria-label’] |
Inner Text Conundrum:
One of the most easily readable syntaxes yet powerful. You can make use of this mechanism to identify text anywhere on the DOM using a string pattern.
Syntax:
1 |
<HTML Tag> <:> <contains> < (text) > |
Example
1 |
div:contains("^lambdatest$") |
“Navigating Through Child Elements” – Child Conundrum:
This is an advanced way of handling the element locators through CSS selectors in Selenium while navigating through child elements. There are three possibilities as below:
- Direct Child
- Sub Child
- Nth Child
Direct Child
Direct child to the parent locator is represented with a ‘>’ symbol. Let’s assume we have a button tag inside a div tag which happens to be a direct child as shown in HTML snippet below.
Example:
<div class="lambdatest-xs-ng">
<button id="tertiary" class="sidebar-container" role="complementary">
div is parent locator and the button is the child locator is represented as:
div.lambdatest-xs-ng>button
Syntax:
Parentlocator > directchildlocator
Sub Child or Child
Sub child identification includes the same way to identify the elements as that of the direct child but we can ignore ‘>’ symbol as sub child as shown in the example below.
Example:
1 2 3 4 |
<div id="primary" class="content area"> <div id="content" class="site content" role="main"> <header class="archive header"> <h1 class="archive title">Category Archives : Infographics </h1> |
Sub Child or child would be represented as:
1 |
div#primary header |
Syntax:
1 |
<parent locator=""> <child locator=""> or <sub child="" locator=""></sub></child></parent> |
Nth Child For Opting A Specific Value From A List
This is an advanced way of handling the element locators through CSS selectors in Selenium while navigating through child elements. There are three possibilities as below:
- Direct Child
- Sub Child
- Nth Child
Direct Child
Direct child to the parent locator is represented with a ‘>’ symbol. Let’s assume we have a button tag inside a div tag which happens to be a direct child as shown in HTML snippet below.
Example:
1 2 |
<div class="lambdatest-xs-ng"> <button id="tertiary" class="sidebar-container" role="complementary"> |
div is parent locator and the button is the child locator is represented as:
1 |
div.lambdatest-xs-ng>button |
Syntax:
1 |
Parentlocator > directchildlocator |
Sub Child or Child
Sub child identification includes the same way to identify the elements as that of the direct child but we can ignore ‘>’ symbol as sub child as shown in the example below.
Example:
1 2 3 4 |
<div id="primary" class="content area"> <div id="content" class="site content" role="main"> <header class="archive header"> <h1 class="archive title">Category Archives : Infographics </h1> |
Sub Child or child would be represented as:
1 |
div#primary header |
Syntax:
1 |
<Parent locator> <child locator> or <sub child locator> |
Nth Child For Opting A Specific Value From A List
N-th child concept would be useful while navigating through ordered or unordered list elements. N becomes the number of the desired list user wants to select. Let’s go through below example to understand how n-th child works. In o
Example:
1 2 3 4 5 6 |
<<ul id = "lambdaTestBrowsers"> <li>Chrome</li> <li>Firefox</li> <li>Edge</li> <li>Safari</li> </ul> |
Nth child of firefox from the list of lambda test browsers would be represented as:
1 |
#lambdaTestBrowsers li:nth-child(2) |
Syntax:
1 |
<HTML Tag> <Clas or ID> <list> <:> <nth-child (number of desired item in the list)> |
Conclusion
We have come across different identification strategies through the above element locator conundrums. To get familiar with CSS Selectors in Selenium by querying you make use of Chrome dev tools and also there is an open-sourced tool for the same to try out and view results more interactively at http://flukeout.github.io/. We also discussed the benefits of using CSS selectors in Selenium over other element locators. One of the major drawbacks of the CSS selectors in Selenium is traversing the DOM is not possible with CSS as that of XPath. We can navigate from child to parent and parent to child using XPath. But we can only navigate from parent to child by CSS Selectors in Selenium. If you have any queries or suggestions regarding the CSS Selectors please drop a comment below and I would love to interact. Have fun locating elements through CSS Selectors. Happy testing!
Got Questions? Drop them on LambdaTest Community. Visit now