Monday, October 24, 2016

CSS selectors for automation: how to use them

One of the most common problems we face when automating is that the elements' locators become obsolete as soon as there is a change in the UI we are testing, and most of the time the options for this are clear: Xpath or  CSS Selectors. I´m not comparing them in this article, since there's some controversy around the question. I found an interesting article that compared Xpath and CSS Selectors in terms of performance and other metrics, you might want to check it out. So, there are many reasons to use CSS Selectors. Now, I´ll show some basic tricks with CSS Selectors with a framework with Java and Selenium in mind.


Select by ID
Select by tag
Select by class
Select nth element


  1. First of all, open Firefox. We will use this page ( for the examples, so open it in a new tab. 
  2. Now, right click on the Testools logo > Inspect Element with Firebug.Inspect logo
  3. Click FirePath.
  4. Click the button at the left of the text box and select CSS. Here we will test our CSS Selectors.CSS text box

Select by ID

First, let's check the HTML structure for the logo:
Logo ID
As you can see, the id for the Logo is Header1_headerimg. In CSS Selectors, IDs are selected using #. So, in this case, we can select the logo with this:


Open the FirePath tab and paste that string, then press Enter. You should see a match:
Selected logo element

Since IDs should be unique, using them is a safe way to select elements for Selenium. However, not all elements have a unique ID, and asking developers to add them is not always an option.

Select by tag

You can select elements by tag, although this is better used in along with classes. However, tags are selected only with the tag name itself. If you'd want to select all the elements with the tag img, like this:
img tag

You'd only need to write this:


And it will match all the elemts with the img tag:
Selection by tag

Select by class

Classes are selected using dots. For example, if we want to select the first post:
Posts inspection
We can do it by typing the class name preceded by a dot:


This will select all the elements with the class wrapfullpost. In this case, 5 elements are selected, since there are 5 posts in the main page:
Select by class

Select nth element

In the example above we had 5 elements selected. But what if we want to select only one of those elements? Let's check another example. Enter the following css:

That will select the menu:

Menu selected

If we expand the selected element, we will see that the four menu elements are represented by 'li' nodes. To select the 3rd element, we can use: li:nth-of-type(3)

3rd element

Note that, to select the first element you should use nth-of-type(1). Unlike most of other syntax, here you start the count in 1.

This will be enough to get you started using css selectors!

0 comentarios:

Post a Comment