CSS Locators In Selenium – A Detailed Guide

Last updated on : Jul 10, 2023 by Shubham Srivastava

Do you want to know – What are CSS Locators in Selenium Framework? and Different Selenium CSS Locator with examples?

Great !! You have reached to the final destination. In this post, we learnt about the same topics. So, without any delay, let’s get started –

CSS Locators are also called as CSS Selectors in Selenium. We can use CSS Locators in our Selenium Test Scripts to identify any Web Element, But before going deep into CSS Locators in Selenium, we must know – What is CSS? Then, we will learn about – What are CSS Locators? and How they can help us to locate Web Elements in Selenium?

Note** This in-depth Selenium tutorial is part of our free Selenium Framework Mastery Series. In case, if you are also interested to learn about other important topics of Selenium, then check the link after this Selenium guide.

Let’s get started with CSS Selectors Tutorial –


What are CSS and CSS Locators ?

CSS is basically a styling language. CSS is a short of Cascading Style Sheets, that helps any website to look colourful and in proper layout. Along with HTML, CSS is fundamental pillar of web designing. Without CSS, websites would still be plain text on white backgrounds with minimum colours and graphics, something like below-

Website - With CSS and Without CSS

What are CSS Locators?

CSS Locators are also known as CSS Selectors. Till the date this tutorial was written, to test the CSS Selectors / CSS Locators live in browser console / developer tool, you need to use – Chrome / MS Edge / Safari browser but not the Firefox.

There are five types of CSS Selectors that can also be used in Selenium tests to write XPath or locate web elements :

CSS SelectorSymbolSyntaxExample
ID# (hashtag)#idValue
Or
tagName#idValue
#email
Or
input#email
Class. (dot).classnameValue
Or
tagName.classnameValue
.center-text
Or
input.center-text
Attribute[ ] (brackets)tag[attributeName=value]input[type=’password’]
Sub-String^ , * , $tagName[attribute^=’substring’]button[class^=’signup’]
Inner String(A Text)tagName[contains(text(),”string”)]//button[contains(text(),’Sign up’)]

Types of CSS Locators

1] id – CSS Locator

  • Syntax 1 =
    elementTagName#idValue
  • Syntax 2 =
    #idValue
  • Example =
    input#email
  • ID is an attribute of a web element.
  • The hash sign ‘#’ should always be present when you are using a Selenium CSS Selector with ID.
  • Using ID of an web element, you can locate it very precisely.
  • Now, if you think – Which one is the best locator in Selenium WebDriver?, then remember, if ID is available of the element, then ID is one of the most preferred CSS Selector / Selenium Locator.

Note :
If there are multiple web elements in a Web page and each web element is having the ID attribute, then you can take advantage of this situation. To search for each of such elements having ID attribute, you just need to write ‘#IdAttributeValue’ of that element, and you will be able to find out that web element. ID attribute values are unique for every web element in a Web page, means, on a webpage, No two ID attributes value would be same.


2] class – CSS Locator

  • Syntax = tagName.className1.className2
    Or Syntax = .className1
  • Example = input.send-msg.btn
  • There might be chances that same class names is given to multiple buttons, input text boxes or other elements, so be careful while targeting a specific web element using CSS Locator / CSS Selector.
  • To use class CSS Selector, you need to use the dot (.) symbol before each of the class name.
  • class attribute can have multiple values separated by white space.
CSS Selector Using Class Attribute

3] attribute – CSS Locator

  • To locate element, we can use attribute of that web element.
  • You need to use brackets [ .. ] . Inside this bracket, you need to specify attribute name, put equals to ‘=‘ and provide the value.
  • The value will be the term, using which you are going to locate all the required web elements.
  • In the below example, we have used tag – attribute CSS Selector and created the expression => button='uplText'

4] substring – CSS Selector

  • substring CSS selectors allow us to locate all such web elements that contains text inside them and we searched with a part of their text (substring).
  • There can be multiple situations when you decide to search with a string. For each situation you can use specified character to locate web element –
SituationCharacterExample
a) Matching with starting part (prefix) of a full string.^input[aria-label^=”I’m”]
b) Matching with ending part (suffix) of a full string.$input[aria-label$=”Lucky”]
c) Matching with a part of string from the mid of a full string.*input[aria-label*=”Feeling”]

Let’s see live example to use substring CSS Selector in different situations (prefix, suffix, and in-mid).

a) Search Web Element from Prefix –

  • Here, we have searched a Google page’s input web element, which is having
    text = ‘I'm Feeling Lucky‘.
  • We have searched that web element using prefix substring of its string,
    that is = I'm.
  • Here’ we have used the XPath = input[aria-label^="I'm"], which contains caret symbol ^
  • This caret symbol ^ tells the browser engine to search for the substring which is present in the starting of some other string.

b) Search Web Element from Suffix –

  • In the above example we have used suffix based substring (text = ‘Lucky‘) to find out the input web element having
    text ‘I'm Feeling Lucky
  • Observe, the pattern / XPath = input[aria-label$='Lucky'].
  • Here, we have used the dollar symbol $ to tell the browser engine to look for the substring from the end.

c) Search Web Element from text in middle –

  • In the above example, we have used the asterisk symbol * to create XPath with substring.
  • The created XPath = input[aria-label*='Feeling'].
  • Here, we are telling the browser engine to look for the substring that must be present in the middle of some other string.

5] innerText : CSS Locator

The innerText CSS Selector has been deprecated / vanished from the market. Previously we used to use this CSS Locator something like this =

tag: contains(“the inner text to search”)

But, now it’s support has been removed from the browser engine and now to achieve that functionality to locate Web Element, we need to use the contains(_ , _) method to search for the element, something like below =

//a[contains(text(),"Editpad")]

Let’s see a perfect example of this contains() method –


Selenium Code Example with CSS Selector –

If we take above HTML code example scenario and let’s assume we need to uniquely identify that span element which is containing the above bordered anchor tag. Then, in that case here is how we can take help of CSS Selector method of Selenium –

HTML Code –

<span class="logo">
  <a href="/">
    <img src="/imgs/logo128.png?v=1.1" alt="Edit Pad - Free Online Text Editor"
    width="16" vspace="0" hspace="2" height="16" border="0" align="bottom">
    Editpad
  </a>
</span>

CSS Selector Syntax –

In this scenario to find locate the span element, we can take help of class CSS Locator. We use the . (dot) notation.

Selenium Code –

The Selenium code to click on the span element using cssSelector() method would be like –

WebElement element = driver.findElement(By.cssSelector("span.logo")); // Finds span element having 'logo' in class attribute.

// or

WebElement element = driver.findElement(By.cssSelector(".myForm"));   // Finds any element having 'logo' in class attribute.

Conclusion –

In this simple Selenium Automation Testing guide, we have learnt about CSS Locators In Selenium, CSS Selectors as well as different types of CSS Locators with Examples, syntax and more. If you are willing to learn more about Selenium Framework, then mush check this Free Selenium Framework Mastery Series. If you have any query / suggestion, then please drop your thoughts in the comments section below. I’ll try to provide you answer within 21 hours.

Keep Thinking Logical..
Team LogicalDuniya.com
Cheers, Shubham !!

Shubham

Shubham Srivastava

Hey there, my name is Shubham and I'm working as an SDET at a US based FinTech company. I've more than 7 years of working experience and using my knowledge - I want make this platform super helpful for those, who want to solve any software development and testing related problems. Comment your query / request or suggestion in the below section, and I'll try to respond within 24 hours. Keep improving, Keep coding !!

Recommended Posts :


4 1 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

[…] There are many other ways to write CSS Selector patterns. We will learn about them in this CSS Locators session. […]

Press ESC to close