Thursday, April 16, 2020

Selenium Locators - CSS Selector

What is CSS Selector?

CSS selector is the method to locate element based on pattern of CSS (Cascading Style Sheets) used in HTML structure of web page.

It's simple string pattern to identify the web element based on CSS attributes.

What is CSS?

CSS stands for Cascading Style Sheets. CSS describes how HTML elements are to be displayed on screen, paper, or in other media.

Different Types of CSS Selector Locators

1> Tag and ID: # Sign used to Represent ID in CSS Selector locator.

CSS Syntax: <HTML tag><#><Value of ID attribute>

The First name text box has an ID attribute whose value is defined as “Fname”. Thus ID attribute and its value can be used to create CSS Selector to access the first name textbox.


Example: input#fname


2> Tag and Class: . Sign used to Represent ID in CSS Selector locator.

CSS Syntax: <HTML tag><.><Value of ID attribute>

The Div has an Class name attribute whose value is defined as “dRYYxd”. Thus Class name attribute and its value can be used to create CSS Selector to access the that Div.



Example: div.dRYYxd

3> Tag and Attribute: Normal syntax we need to follow to match attribute name and value as below.

CSS Syntax: <HTML tag><[attribute=Value of attribute]>

The password text box have different attributes value and we are using the combination as we did in xpath to match with attribute name = attribute value to locate the password field.


Example: input[id=pass]


4> Tag, Class & Attribute: Here we are using multiple objects to locate the element.

CSS Syntax: <HTML tag><.>ClassName<[attribute=Value of attribute]>

The search box have class name and attribute details as show in screenshot and we use combination as below to locate the same.



Example: input.gLFyf gsfi[title=Search]

Sub-String Matches Method

In CSS Selector also we can use string information to locate the element like we do on advance XPath methods. Using below methods we can handle dynamic elements on web page.


1> Starts-with (^): Represents the starting text in a string.

CSS Syntax: <HTML Tag>[<AttributeName> ^ = <AttributeValue>]

As per below screenshot we have to select Password field which have name start with word 'Pass', so we can locate it as below CSS Selector.



Example: input[name^=pass]


2> End-with ($): Represents the ending text in a string.


CSS Syntax: <HTML Tag>[<AttributeName> $ = <AttributeValue>]

As per below screenshot we have to select Password field which have end with word 'word', so we can locate it as below CSS Selector.



Example: input[name$=word]


3> Contains (*): Represents the sub string in a string.


CSS Syntax: <HTML Tag>[<AttributeName> * = <AttributeValue>]

As per below screenshot we have to select Password field which contains sub string word 'ss', so we can locate it as below CSS Selector.


Example: input[name*=ss]


No comments:

Post a Comment