In the Previous Tutorial, we took a deeper dive to the XPath ocean and learned to construct partial XPath by using the following XPath functions:
- wild-card *
In this tutorial, we will learn to locate elements through CSS selectors.
CSS Selectors are said to be faster than XPath and at times it could be very useful.
What is a CSS Selector?
Every modern web page is build of CSS. They define the cosmetic behavior (e.g. size, fonts, inclination, etc) of the whole page and/or object(s) inside the page. CSS rules do the grouping of class names of objects to define the combined cosmetic behavior of those objects. Similarly, they use Object’s id property to define an individual object’s look and feel.
Writing CSS Selectors
- Let us launch Chrome and navigate to http://www.imdb.com/
- Inspect the IMDb logo at the top-left of the page.
- Let us look closely at the source code for this element
<a id="home_img" class="navbarSprite home" title="Home" href="/?ref_=nv_home" onclick="(new Image()).src='/rg/home/navbar/images/b.gif?link=%2F%3Fref_%3Dnv_home';"></a>
As we can see the element has the tag
a. It has the following properties –
onclick. We can write a CSS Selector like this:
It is saying target the element that has
a tag. The
# after the tag name means to look for the
id attribute value. So the target element should have an
id property and its value must be
We can verify the CSS locator in the browser. Check this link if you missed how to do it.
We can use a
. to indicate class. For the same element, we can write a CSS selector to target class:
The complete value of the class attribute is ‘navbarSprite home’. Why you are using only one part – navbarSprite?
Well, as I said at the start of the post, CSS rules group together several objects by their class name to give them common cosmetic behavior. A single object can have a class property that has more than one values separated by space.
In our case, the object belongs to two classes –
home. In these scenarios, we can target only one class if that uniquely locates the element.
However, we can also try this:
CSS Selector equivalent to XPath
|Locate an <input> with ID attribute ‘username’||
|Locate an <input> with CLASS attribute ‘password’||
|Locate a <span> that is DIRECT CHILD of <div>||
div > span
|Locate <span> that is CHILD or SUBCHILD of <div>||
|Locate a link <a> with inner text ‘Log out’||
|Locate an element with any attribute that has a value (full match)||
| Locate an element with an attribute that has value – prexyzsuf
Contains a value ‘xyz’ (partial match)
Starts with a value ‘pre’
Ends with a value ‘suf’
Not supported by XPath 1.0
|Locate an element with tag name not specified (wildcard)||
//*[@alt='searchIcon'] //*[@id='search'] //*[@class='product']
[alt='searchIcon'] #search .product
We learned all the possible ways to locate elements. In the Next Tutorial, we will explore ways to perform the action on those elements.