Identifying elements in the page | CSS Selectors

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:

  • contains()
  • starts-with()
  • text()
  • wild-card *
  • Indexing

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

Target id

  • 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 – id, class, title, href and onclick. We can write a CSS Selector like this:

a#home_img

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 home_img.

We can verify the CSS locator in the browser. Check this link if you missed how to do it.

Target class

We can use a . to indicate class. For the same element, we can write a CSS selector to target class:

a.navbarSprite

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 – navbarSprite and home. In these scenarios, we can target only one class if that uniquely locates the element.

However, we can also try this:

a.navbarSprite.home

CSS Selector equivalent to XPath

ActionXPathCSS
Locate an <input> with ID attribute ‘username’
//input[@id='username']
input#username
Locate an <input> with CLASS attribute ‘password’
//input[@class='password']
input.password
Locate a <span> that is DIRECT CHILD of <div>
//div/span
div > span
Locate <span> that is CHILD or SUBCHILD of <div>
//div//span
div span
Locate a link <a> with inner text ‘Log out’
//a[text()='Log out']
a:contains('Log out')
 Locate an element with any attribute that has a value (full match)
//p[@name='Submit']
p[name='Submit']
 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’

//p[contains(@name,'xyz')]
//p[starts-with(@name,'xyz')]

Not supported by XPath 1.0

p[name*='xyz']
p[name^='pre']
p[name$='suf']
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.

21 thoughts on “Identifying elements in the page | CSS Selectors”

  1. To search id
    **************
    css=button#navbar-submit-button

    To search with class
    **************
    css=button.primary.btn

    Please note that –> class="primary btn" in class name we have a single space,,, so i need to used '.' for the space by checking on internet.

    Questions
    ***********

    Q1) What if there are mutliple spaces in class name ?

    Q2) is there a shortcut to open selenium ? Because i need to press 'alt+tab' again to switch between tutorial page and selenium or click on the top right

    Such assigments are great where we need to try things.(as there was a space between class name… please give such assignments so we face some difficulty.

    Regards
    Gaurav khurana

    http://www.udzial.com
    Udzial Means Share

    Reply
  2. You did the job man. There is a reason I did not cover that part in this basic css tutorial. I wanted to keep few things for advanced css part. You did good research. But one thing, don't treat them as spaces between the class name. In actual, they are different classes. If you see the css rules in FireBug you can check two different/same rules for those two different classes.

    Shortcut for Selenium IDE – Ctrl+Alt+S . Before hitting keyboard, make sure Firefox is the active opened application (at front of the screen).

    Reply
  3. if you dont specify tagname it will treat it as wildcard type like * in case of xpath… any matching… it works for you in this case because that is the only matching id… however it may happen that the same id 'navbar-submit-button' is present inside two different tags….better approach is to specify the tag to make sure uniqueness… although that is also not surety

    Reply
  4. Hi,

    Thanks for explaining the concepts in such an easy language!!!

    Here is my question:
    I am unable to figure out the scenarios as to when to use XPath to find objects and when to use CSS?
    I understood they are different approaches to locate object but then what is the exact use case for either of them?
    As you mentioned,when the properties of an object are not unique we use XPath to locate objects.So when we have XPath, then why is CSS required?

    Reply
  5. Hi Anjali

    Good question! In general, CSS selectors are just one more way to identify elements. CSS locators work faster than xpath, specially on IE. In real world projects, sometimes there are cases when you try to perform some action on elements identified using other locators, WebDriver throws an exception – "element is not visible and cannot be interacted with". In this case if you use css locators, there are chances that you may avoid that exception. However, xpath has so many in-build functions that you can use like selecting sibling, child, parent etc. Confused, which one to use??? Choose what works best for you in that scenario, and it will come with experience.

    Regards,
    Shadab

    Reply
  6. css=button#navbar-submit-button
    css=button.primary
    css=button.primary.btn
    css=button.btn

    Also, It would be great if you can give more such assignments and with more complexity. I'm loving it 😉

    Reply
  7. This is very interesting to find elements 🙂 thanks a lot

    As in the assignment,i was success in finding elements by below CSS locators
    css=button.primary
    css=form button
    css=div>button
    css=button[type=’submit’]

    but
    1.i was not able locate by using id , i have used below comment .Please advise
    css=button#navbar -submit -button

    2.Since this element has no inner Text , we can not user text() any where right ? Please correct me if i am wrong.

    Reply
      • Hi Amrutha

        Apologies for the late response. Somehow your comment was filtered as spam.
        Congratulation for your right approach to assignment. Yes, if there is no inner text for any element you wont use text().

        Thanks
        Shadab

        Reply
  8. Hi Shadab
    Tutorials are quite good.
    Just wanted to know if we can search in css using partial inner text.
    a:contains(‘Log out’)
    In the above case just with Log or out.

    Reply

Leave a Reply to Manali MittalCancel reply