DEV Community

Pcloudy
Pcloudy

Posted on

Understanding CSS Selectors in Selenium

CSS Selectors in Selenium
Selenium WebDriver is one of the popular web automation tools. It is open source and is preferred by many automation engineers to automate the websites. Using Selenium WebDriver is quite simple and easy. We need to follow the following simple steps to write an automated test:

Locate an Element on the WebPage using Browser’s Dev Tools
Using Selenium WebDriver’s findElement/findElements method we need to supply the locator to locate the element on the web page.
Write automation tests and perform assertions.
Before we start writing the test, let’s understand what are locators in Selenium as these are needed in the first step to automate the tests using Selenium WebDriver.

What are locators in Selenium WebDriver?
Locators in Selenium are used to identify and locate web elements on a web page. They can be found by inspecting the HTML source code of the web page by using the Developer tools option provided by the browsers. There are eight different locator strategies that can be used with Selenium WebDriver.

In the following section, we will be discussing the types of locator strategies.

Types of Locators in Selenium WebDriver?
The following are various Locator Strategies supported by Selenium WebDriver:

ID: Used to locate an element by its ID.
Name: Used to locate an element by its name.
TagName: Used to locate an element by its HTML tag.
ClassName: Used to locate an element by its CSS class.
LinkText: Used to locate a link by its visible text.
PartialLinkText: Used to locate a link by the partial value of its visible text.
XPath: Used to locate an element within the HTML document by evaluating an XPath expression.
CSS selector: Used to locate an element by its CSS selector.
What are CSS Selectors?
CSS Selectors are used within Selenium to locate elements on a web page. They are beneficial because they are shorter than XPath locators and allow for a more clear and crisp method to locate the element. They work by using patterns to match tags and their attributes, such as class or ID.

CSS Selectors can be used in combination with each other and can also be chained together. They are supported in all the modern browsers and are a great way to quickly and precisely locate elements within a web page.

There are five types of CSS Selectors in Selenium WebDriver:

Using ID
Using ClassName
Using Attribute
Using Substring
Using nth-child
Locating elements using CSS Selectors
Using CSS Selectors is pretty simple and easy, you just need to open the browser’s developer tools, read the DOM and find the values easily.

Copying CSS Selector from Browser directly
Browsers also provide an option to copy the CSS Selectors directly from the DOM, you just need to follow the given steps:

Open the Browser and navigate to the pCloudy website’s Login page, open Developer Tools in Chrome Browser by pressing F12 key or clicking on the three dots below the “X” button >> More tools >> Developer Tools

Image description

Now let’s try to locate the CSS Selector for email Id field by inspecting the field >> right click on the DOM element >> Copy >> Copy Selector

Image description

Press Ctrl + F to open the finder in the DOM and paste the value we just copied by pressing

Ctrl + V. It should have copied the “ID” of the field #userId

Image description

We can also write the CSS Selectors by inspecting the elements manually from the DOM using the following:

With ID
Syntax

<#>

While Using CSS Selector, “#” is used to locate an element with an ID.

Let’s take the example of the Login page of pcloudy.com website and locate the email field. Below is the Screenshot of the page, we can notice that ID for the field is “userId”

Image description

We can use #userId as CSS Selector for locating this field and write the code as

driver.findElement(By.cssSelector(“#userId”)) in our Selenium tests.

Image description

Using ID with TagName
Syntax

<#>

In the example we saw above for the email field on Login Page we see that HTML tag is used for the email field.

We can combine both the HTML Tag and ID and use it for locating the email field and use the CSSSelector as input#userID.

Image description

Using ClassName
Syntax

<.>

(.) – A Period/Dot refers to the Class attribute in CSS Selector. In the example we saw above for the Login Page, let’s locate the Welcome header text using ClassName, below is the screenshot of the Page

Image description

Here is the DOM

Image description

Welcome Text is in the h1 Tag element which is child of class – “p-16”, class “p-16” is a child of “d-flex” class whose parent is “signup-row” class and finally “normal_login_container” is the top node class. Hence the CSS Selector for this Welcome header will be .normal_login_container .signup-form > .d-flex > .p-16 > h1.text-center

The dot before the name refers to class.

Note the “>” sign before “.d-flex” in the CSS Selector, it is used for selecting the class that is a direct descendant of “.signup-form” class. Similarly “>” after other class names as well.

Using Attributes
Syntax

<[attribute =’value of attribute’]>

An attribute can be a value, type, name, etc. which could be a unique value that allows to identify the web element.

Note: Value of the attribute needs to be supplied in single quotes.

In the example of the email field we saw above, there is a tag having attribute as “type=email” and “name=userId”:

Image description

We can use the CSS Selector for the email field using name attribute follows:

input[name=’userId’]

Image description

Using combination of type and id attribute

Lets now try to locate the Login button by providing multiple attributes.

So, if we see in the screenshot below we see that the HTML tag is and has the attribute type as “button”, also it has the attribute id as “loginSubmitBtn”.

Image description

By combining both of these two we can write the CSS Selector for locating the Login button as

button[type=’button’][id=’loginSubmitBtn’]

Image description

Using SubString
CSS Selectors also allow the flexibility to match the partial strings to locate an element on the web page.

Matching partial Strings can be done in the following 3 ways:

Matching a Prefix (Starts With)
Match a Suffix(Ends With)
Matching a Substring(Contains)
Matching a word(Contains)
Match a Prefix
Syntax

<[attribute^=’prefix of the string’]>

(^=) is used to match the string using a prefix.

Let’s take the example of the password field from the Login Page and try to locate it using the prefix of the name attribute.

Image description

The name attribute for the field is “password”, we can write the CSS Selector as

input[name ^=’pass’] as it starts with ‘pass’.

Image description

Match a Suffix
Syntax

<[attribute$=’suffix of the string’]>

($=) is used to match the string using a suffix.

Let’s take the example of the password field from the Login Page and try to locate it using the suffix of the name attribute.

The name attribute for the field is “password”, we can write the CSS Selector as

input[name$=’rd’] as it ends with ‘rd’.

Image description

Match a Substring
Syntax

<[attribute*= ‘Substring’]>

(*=) is used to match the string using a substring.

The name attribute of the email field is “userId”, we can write the CSS Selector as

input[name*=’ser’]

Image description

Match a word
Syntax

<[attribute~=‘word’]>

(~=) is used to match the word.

Let’s take the example of the Phone field from the pCloudy’s Signup page and try to locate it using the matching word of the ClassName for the respective country codes.

Image description

The Class Name for the country code dropdown list field is “‘iti__country”, we can write the CSS Selector as

li[class~=’iti_country’] and it will locate all the respective elements containing the classname iti_country.

Image description

Using :nth-child
Syntax

:nth-child(n)

nth-child matches every element that is the nth child of its parent.

Let’s take an example of the Country list dropdown displayed in the Phone field on the signup page of pCloudy website.

Image description

This field has multiple

  • tag elements, we can use the nth-child selector to iterate through this list and select the required element.

    So, if we want to select the country code of Algeria(it is 6th child), so we can write the CSS Selector as ul> li:nth-child(6)

    Image description

    Selecting the first child
    Now, if we want to select the first country code in the list we can use the CSS Selector as ul> li:first-child. It selected “United States” in the list as it is the first child.

    Image description

    Selecting the last child
    Similarly, to select the last child we can use the CSS selector ul> li:last-child

    It selected “Åland Islands” as it is the last child.

    Conclusion
    CSS Selectors selectors are easy, precise and simple to use in Selenium tests and these selectors provide flexibility to the user so he can create his own selector and use it to find an element. It also adds to the readability part as CSS selectors are easily readable and understand which field we are referring to.

    I would suggest trying your hands on locating the elements in your selenium tests by using CSS Selectors.

    Happy Testing!

  • Top comments (0)