CSS Selectors in Selenium

Selenium provides a variety of approaches to locating web items based on properties like id, name, className, etc. However, there are situations in which utilizing a straightforward attribute locator to find a web element is not feasible while working in a dynamic context. Selenium’s CSS selectors come to assist in these inflexible circumstances. Explore what is new in Selenium 4 and join SLA Jobs for hands-on exposure to it. 

Selenium: An Overview

The web automation tool Selenium WebDriver is one of the most widely used. Many automation developers love it since it is open source and can automate websites. Selenium WebDriver is very easy to use and straightforward. Check out the recent software testing jobs in Chennai To write an automated test, we must adhere to these easy steps:

  • Find an Element on the web page using the Developer Tools in the Browser
  • To locate the element on the web page, we must specify the location using Selenium WebDriver’s findElement/findElements method.
  • Create automated tests and execute statements.

Locators: What are they?

In Selenium, locators are employed to recognize and pinpoint web items on a webpage. They can be located by utilizing the browser’s Developer Tools option to examine the HTML source code of the webpage. With Selenium WebDriver, eight distinct locator techniques are available. Explore the top 7 principles of software testing and get accelerated in your testing career.

Types of Locators in Selenium WebDriver

Some of the ‘Locator Strategies’ that Selenium WebDriver supports are as follows:

ID: An element’s ID can be used to find it.

Name: A method for identifying an element by name.

TagName: The HTML tag used to identify an element.

ClassName: A CSS class name that is used to find an element.

LinkText: Used to find a link based on the text that is shown.

PartialLinkText: This function is used to find a link based on the visible text’s partial value.

XPath: Employed to evaluate an XPath expression and find an element inside an HTML document.

CSS selector: A tool for using an element’s CSS selector to find it.

CSS Selectors

Selenium uses CSS selectors to find components on a webpage. They are advantageous because they enable a more precise and straightforward way to locate the element and are shorter than XPath locators. They function by matching tags with their attributes, like class or ID, using patterns. Enroll in our Best CSS training in Chennai for a better understanding of CSS.

CSS selectors can be linked together or used in combination with one another. They are a terrific way to easily and precisely pinpoint elements within a web page, and they work with all modern browsers. In Selenium WebDriver, CSS selectors are available in five different types:

  • Using ID
  • Using ClassName
  • Using Attribute
  • Using Substring
  • Using nth-child

Using ID:

In XPATH, an element’s id is declared as follows: “[@id=’example’]”. and using “#” in CSS The IDs must be distinct in the DOM.

XPath: //div[@id=’example’]

CSS: #example

Element Type: In the preceding example, //div was visible in the XPath. That is the element type, which could be “a” for a link, img for an image, or input for a text box or button. 

Xpath: //input or

Css: =input

Direct Child: The structure of HTML pages is similar to that of XML, with children nestled within parents. For example, you can create a string to reach the first link inside a div if you know where it is. In XPATH, a direct child is defined by a “/”, whereas in CSS, it is defined by a “>”.  

Example:

XPath: //div/a

CSS: div > a

Child or sub-child: It can be tedious to write nested divs, and the resulting code can be fragile. There are occasions when you want to skip layers or expect the code to change. When defining an element in CSS, whitespace is used, and if it can be inside another element or one of its children, “//” is used in the XPATH.

Example: 

XPath: //div//a

CSS: div a

Recommended Article: Trending Software Courses for non-IT Graduates

Using Class

In XPATH, classes behave similarly to each other: “[@class=’example’]”. In CSS, however, it is just “.”

Example:

XPath: //div[@class=’example’]

CSS: .example

Advanced Example:

<form class = “form-signin” role = “form” action = “/index.php” method = “post”>

<h4 class = “form-signin-heading”></h4> 

<input type = “text” class = “form-control” id = “username” name = “username” placeholder = “username” required autofocus></br> 

<input type = “password” class = “form-control” id = “password” name = “password” placeholder = “password” required> 

<p> 

<button class = “btn btn-lg btn-primary btn-block radius” type = “submit” name = “login”>Login</button> 

</form> 

Now let’s construct an XPath and CSS selector to determine which input field should come after “username.” If the form is rearranged, this will choose a different element or the “alias” input.

Example

XPATH: //input[@id=’username’]/following-sibling:input[1]

CSS: #username + input

Using Attributes

Selenium’s attribute selector allows you to choose elements based on any attribute value if the ordering of the child elements is not important to you. A nice illustration would be selecting the ‘username’ field on the form above without including a class.

Without giving the username element a class or ID, we may choose it with ease.

XPATH: //input[@name=’username’]

CSS: input[name=’username’]

To use our selectors more precisely, we can even chain filters.

XPATH: //input[@name=’login’and @type=’submit’]

CSS: input[name=’login’][type=’submit’]

Explore the highest-paying software jobs for freshers and experienced professionals. Get expertise with the required skills through SLA.

Using Sub-string 

One noteworthy feature of Selenium’s CSS is that it supports partial-string matches with operators like ^=, $=, or *=. After defining each, I’ll give an example of it.

^= Match a prefix

CSS: a[id^=’id_prefix_’]

$= Match a suffix

CSS: a[id$=’_id_sufix’]

*= Match a substring

CSS: a[id*=’id_pattern’]

Using Combined Attributes

Using the same example as before, we have an HTML structure with the class, placeholder attribute, and textarea tag. Afterward, we can combine them to make a CSS selector that will help us find the web element, as the example below illustrates:

textarea.form-control[placeholder=’Current Address’]

  • First, we worked with the textarea HTML tag.
  • Next, we utilized the class symbol, which is ‘.’ or a dot
  • Next, we supplied the class attribute’s value.
  • Finally, we supplied the placeholder attribute and its value inside the square bracket.

Thereby, we may locate the web element in Selenium uniquely by combining several HTML element properties.

Suggested Read: Selenium Interview Questions and Answers

Ways to locate dynamic web elements with a CSS selector

Several times, web pages are generated dynamically using the always-expanding new technology in web development. Because there is no direct locator for some web elements, there will be a variety of scenarios where those elements display on the page depending on particular conditions or actions only. Selenium offers several methods for finding these dynamic web items, including:

  • Locating the element associated with the Parent/Child hierarchy
  • Employing text strings to locate the element
    • Starting text
    • Ending text
    • Contains text

Now let’s see how these techniques can be applied to find dynamic web elements on a webpage:

Locating the element associated with the Parent/Child hierarchy

With CSS selectors, you can go from one element to another by utilizing the parent element’s locator to choose an element. Syntactically, the CSS selector for finding the child element looks like this:

Parent_locator > child_locator

div>textarea[placeholder=’Current Address’]

In this case, the parent locator was utilized first, then “>,” and last, the child locator. By adding another “>” and another locator, this can also be extended to the subchild.

Are you aware of the TCS salary for freshers in 2023?

Employing text strings to locate the element

Like XPath, CSS Selector also lets users find elements with incomplete strings. To indicate the beginning, end, and contents of a text, it employs several symbols. Let’s examine a few instances to gain a deeper understanding of CSS Sub-Strings.

Starting Text

Using the element’s initial text, we can find its location. Knowing the element attribute’s beginning text is helpful. Using CSS selectors, we may find the element by using the attribute value’s initial character sequence.

‘^’ is the symbol used to denote a string’s beginning text.

The expression for finding the web element in the CSS selector using this symbol is:

input[id^=’userN’]

Here, the id attribute has been utilized. “userName” is the value of the HTML’s id attribute. We have used the expression’s first five characters in this expression. From the start, we can employ any number of characters.

Ending Text

We can identify the element similarly using the ending text, as we do with the starting text. Any web element can be found using the property value’s last character sequence.

The symbol “$” is used to denote a string’s final text.

The expression for finding the web element in the CSS selector using this symbol is:

input[id$=’ame’]

Once again, the id attribute with the value “username” is used in this instance. In this case, the attribute value’s final three characters have been used. The value and attribute may vary depending on the circumstances.

Contains Text

In Selenium, the CSS Selector has additional options besides starting and ending, such as ‘contains text()’. It can use any sequence of characters from the property value to locate the element.

The following text appears in the symbol for the: “”*

The expression for the elements mentioned earlier in CSS Selector will be the same, using the same symbol:

input[id*=’erNa’]

Here, we have located the element using the HTML “username” as the middle character of the id attribute value.

Find here what is the software testing course fee in Chennai

Conclusion

One of Selenium’s most potent techniques for identifying components on a web page is a CSS selector. It locates and recognizes the element using the web page’s Cascading Style Sheets. Additionally, it can mix many CSS expressions, attributes, and text to precisely point to the needed element. Enroll in our Selenium training in Chennai at SLA Jobs.