info@pragmatictesters.com +94 11 253 8512


Introduction

Learning and mastering a powerful location strategy is a must in Selenium test automation. CSS and XPath are the most powerful location strategies against other options available such as ID, name , tagname, link, partialLink etc. Intent of this blog post is to help Selenium test automation engineers, especially the beginners to understand the importance of mastering location strategies and set a path to master CSS location strategy. We have discussed about XPath in detail in a Separate Blog post already and this blog post explains about CSS location strategy within the context of Selenium test automation.

In the beginning of this blog post  discusses about the comparison of CSS and XPath in the context of Selenium test automation and practical usage of CSS and few pain point are shared in the next section. Number of CSS options available with syntax, HTML snippet and examples are discussed in following sections. XPath to CSS conversion tools, automatically CSS capturing tools are discussed at the end of this blog post. We have used wide range of online resources, lessons learned from our public training classes into this blog post. Happy test automation!

CSS or XPath

CSS and XPath are the most popular, widely used and powerful location strategies within the Selenium test automation community. CSS has gained wider acceptance from the test automation engineers due to following reasons. (People in favour of CSS says)

  • CSS more readable ( simpler )
  • CSS is faster (especially in IE)

Those who are in favour of XPath says about it’s ability to transverse  around the page where CSS cannot. XPath can traverse up and down the DOM. CSS can traverse only down the DOM.

These claims may be already outdated. Some research demonstrate that there is no significant difference in speed.

    • Mastering both of them is a good idea for the Selenium test automation engineers who wish to build their career around Selenium.
    • It is better to a use single location strategy for a project for number of reasons.
    • Some gurus advice hybrid approach. They use ID first and moving to CSS and  XPath is used only when it is required.

Good Locators Are

Please keep following in your mind when selecting a locator. A good locator is,

    • Unique
    • Descriptive
    • Unlikely to change

Sample HTML  Page

Following simple HTML is used in most of the CSS examples in this blog post.

<html><body>

<form id=’login’>

<input name=’txtUserName’ id=’txtUsername’ type=’text’ class=’userName’ >

<input name=’txtPassword’ id=’txtPassword’ type=’password’ class=’password’ >

<input name=’submit’ id=’btnLogin’ type=’submit’ class=’button’>

</form>

</body></html>

Locating Elements by its Attributes

Syntax : elementName[attributeName=’value’]

<input id=”txtUsername” type=”text” name=”txtUsername”>

Following are possible CSS

      • input[id=’txtUsername’]
      • input[name=’txtUsername’]
      • input[type=’text’]

 

Third CSS should not be used even though it is a valid CSS. It is not unique. There could be many elements with attribute type=’text’.

Locating Elements by ID

In CSS # sign is used for locating the elements by value of ID.

elementName#valueofID  or  #valueofID

Examples :

input#txtUsername #txtUsername

Locating Elements by Class

Locating element by single class

<button class=”btn btn-primary btn-block” tabindex=”3″ type=”submit”>Sign in</button>

Examples :

button.btn-primary

.btn

Locating elements by multiple classes

elementName.class1.class2.class3 or .class1.class2.class3

<button class=”submit btn primary-btn flex-table-btn js-submit” type=”submit”>  Log in

</button>

Examples :

button.btn.primary-btn

button.submit.btn.primary-btn

.btn.primary-btn

.submit.btn.primary-btn

Locating Elements by Class and Attribute

elementName.class[attributeName=’value’]

<button class=”submit btn primary-btn flex-table-btn js-submit” type=”submit”>

Log in

</button>

Example :

button.primary-btn[type=’submit’]

Locating Elements with more than one Element

  • elementName[attribute1=’value1’][attribute2=’value2’]…[attributeN=’valueN’] Or
  • [attribute1=’value1’][attribute2=’value2’]…[attributeN=’valueN’]

<input id=”txtUsername” type=”text” name=”txtUsername” class=’userName’ >

Examples :

input[id=’txtUsername’][name=’txtUsername’]

input[id=’txtUsername’][name=’txtUsername’][type=’text’]

[id=’txtUsername’][name=’txtUsername’]

[id=’txtUsername’][name=’txtUsername’][type=’text’]

Locating Child Elements by Element Name

Locating direct child or sub child

<form id=”frmLogin” method=”post” action=”/index.php/auth/validateCredentials”>

<div id=”divUsername” class=”textInputContainer”>

<input id=”txtUsername” type=”text” name=”txtUsername”>

</div>

…..

</form>

<CSS of Parent Element><space><elementName>

Example :

form#frmLogin input

Locating direct child

CSS-of-Parent Element  > elementName

Example :

form > div > input

Locating Nth Child Elements by Element type

CSS-of-Parent-Element elementName:nth-of-type(N)

<form id=”frmLogin” method=”post” action=”/index.php/auth/validateCredentials”>

<input id=”txtUsername” type=”text” name=”txtUsername”>

<input name=”txtPassword” id=”txtPassword” type=”password”>

<input name=”Submit” class=”button” id=”btnLogin” value=”LOGIN” type=”submit”>

</form>

Example :

To locate the password field

form#frmLogin input:nth-of-type(2)

Locating First Child Element by Element Name

CSS-of-Parent-Element  elementName:first-child

Example :

To locate the submit button

form#frmLogin input:first-child

Locating Last Child Element by Element Name

<CSS of Parent Element><space><elementName>:last-child

Example :

To locate the submit button

form#frmLogin input:last-child

Locating Elements by Prefix of the (starts-with) Attribute Value

elementName[attributeName^=’prefix-of-the-value’]

<input id=”txtUsername” type=”text” name=”txtUsername” class=’userName’ >

Examples :

input[id^=’txtUser’]

input[name^=’txtUser’]

Locating Elements by Suffix of the (ends-with) Attribute Value

elementName[attributeName$=’suffix-of-the-value’] or *[attributeName$=’suffix-of-the-value’]

<input id=”txtUsername” type=”text” name=”txtUsername” class=’userName’ >

Examples :

input[id$=’Username’]

input[name$=’name’]

*[id$=’Username’]

*[name$=’name’]

Locating Elements containing part of the Attribute Value

elementName[attributeName*=’part-of-the-value’]

<input id=”txtUsername” type=”text” name=”txtUsername” class=’userName’ >

Example :

input[id*=’User’]

input[name*=’User’]

Locating Next Sibling of a Known Element

<CSS-of-element> + siblingElement

<form id=”frmLogin” method=”post” action=”/index.php/auth/validateCredentials”>

<input id=”txtUsername” type=”text” name=”txtUsername”>

<input name=”txtPassword” id=”txtPassword” type=”password”>

<input name=”Submit” class=”button” id=”btnLogin” value=”LOGIN” type=”submit”>

</form>

Example :

To locate the password field

input#txtUsername + input

Locating Element by Part of the Inner Text

elementName:contains(’part-of-the-value’)

<a href=”/index.php/auth/logout”>Logout</a> Example : a:contains(‘Logout’)

Combining CSS selectors

You can combine selectors with commas.

CSS1 , CSS2

Example :

#txtUsername, .userName

This could be useful in Selenium context when you know one of the CSS will be available at the time of test execution

Locating Elements by Attributes with Case Sensitivity

elementName[attributeName=’value’ i]

<input id=”txtUsername” type=”text” name=”txtUsername”>

Examples :

input[id=’txtusername’ i]

input[name=’txtusername’ i]

It’s the “i” at the end which would do the trick.

    • Your browser might not support it yet.

Practice CSS

There are online resources available to practice CSS.

Game for practicing CSS

A nicely designed little game to help you learn CSS selectors and type in the correct selector to complete each level. You can jump to a level by opening the menu with the hamburger icon on the right.

http://flukeout.github.io/.

Verify CSS

It is important to ensure you use valid CSS in Selenium test scripts and the verification should be done before running the Selenium scripts.

Using Firepath

Install Firebug on Firefox browser. Then install FirePath which will appear as an addon to Firebug.

  1. Open Firebug (using context menu in web page).
  2. Select FirePath Tab.
  3. Select CSS from drip down. Type the CSS
  4. Click Eval button to verify the CSS

selenium test automation

Using FireFinder

You can use FireFinder also to verify the CSS (also for XPath)

  1. Open Firebug (using context menu in web page).
  2. Select FireFinder tab.
  3. Type the CSS
  4. Click Filter button to verify the CSS
  5. Matching element(s) will be displayed

qqqqqqqqqqqqq

Converting XPath into CSS

There are tools helping you to convert XPath into CSS. These are useful if you wish to migrate from XPath to CSS

    • Cssify  by Santiago Suarez Ordoñez

Common notes on using CSS Syntax

Use single quotation instead of double quotations and have to use the negation character if you wish to use double quotations.

Example :

driver.findElement(By.cssSelector(“input[name=\“txtUsername\“]“)).sendKeys(“Pragmatic”);

Attribute values are case sensitive

Example :

driver.findElement(By.cssSelector(“input[name=’txtusername’]”)).sendKeys(“Pragmatic”);

Will not work as exact name is txtUsername

    • Handling case sensitivity is discussed in a separate section

CSS Cheat Sheet (Quick Reference)

CSS Description
#ID Locate an element by ID
.className Locate an element by class name
.className1.className2 Locate an element with with given classes
element[attribute=’value’] Locate an element with an attribute and value
element[attribute1=’value1’][attribute2=’value2’] Locate an element with multiple attributes and values
parentElement > directChildElement Locate direct child of the parent element
parentElement subChildElement Locate an element inside another element
element[attribute^=’prefixOfvalue’]
element[attribute$=’suffixOfvalue’]
element[attribute*=’partOfvalue’]
element :contains(‘innerText’)
element:nth-child(index)
element:first-child
CSS1 , CSS2 Combine the selectors with commas
CSS1 + CSS2 Locate immediately following sibling
CSS1 + * + CSS2 Locate following sibling with an intermediate sibling

Glossary

Term/Abbreviation Description
DOM Document object model
CSS Cascading Style Sheet

References

Arrgyle. 2016. Css Vs. X Path. [ONLINE] Available at: http://elementalselenium.com/tips/32-xpath-vs-css. [Accessed 21 August 2016].

Arrgyle. 2016. How To Verify Your Locators Without Selenium. [ONLINE] Available at:http://elementalselenium.com/tips/verifying-locators. [Accessed 21 August 2016].

Css Selectors | Selenium Testing? Cross Browser Testing with Sauce Labs. 2016. Css Selectors | Selenium Testing? Cross Browser Testing with Sauce Labs. [ONLINE] Available at:http://sauceio.com/index.php/tag/css-selectors/. [Accessed 21 August 2016]

jquery – CSS selector case insensitive for attributes – Stack Overflow. 2016. jquery – CSS selector case insensitive for attributes – Stack Overflow. [ONLINE] Available at:http://stackoverflow.com/questions/5671238/css-selector-case-insensitive-for-attributes. [Accessed 21 August 2016].

Sauce Labs. 2016. Selenium Tips: CSS Selectors | Sauce Labs . [ONLINE] Available at:https://saucelabs.com/resources/articles/selenium-tips-css-selectors. [Accessed 21 August 2016].

Selenium Easy. 2016. CSS selectors for Selenium with example | Selenium Easy. [ONLINE] Available at:https://www.seleniumeasy.com/selenium-tutorials/css-selectors-tutorial-for-selenium-with-examples. [Accessed 21 August 2016].

Selectors Level 3. 2016. Selectors Level 3. [ONLINE] Available at: https://www.w3.org/TR/css3-selectors/. [Accessed 21 August 2016].

Saurabh Gupta. 2016. Quick Reference for Xpath and CSS locators – Selenium WebDriver. [ONLINE] Available at: https://www.linkedin.com/pulse/quick-reference-xpath-css-locators-selenium-webdriver-saurabh-gupta. [Accessed 21 August 2016].

Testing Excellence. 2016. CSS Selectors in Selenium WebDriver with Examples. [ONLINE] Available at:http://www.testingexcellence.com/css-selectors-selenium-webdriver-tutorial/. [Accessed 21 August 2016].

 

Your Turn To Talk

Leave a reply:

Your email address will not be published.