Time for action – finding the nth element with CSS - Selenium

There are times where we need to find the nth element after a parent element on the page.In the XPath examples, we looked at the second input after the div with the class leftdiv. The XPath looked like this: xpath=//div[@class='leftdiv']/input[2]. To find the second to nth element we will need to use pseudo classes. Pseudo classes are used to add special effects to selectors. In this case we are going to use :nth-child for the first example.

  1. Open Selenium IDE.

  2. Navigate to http://www.wisdomjobs.com/chapter(locators).

  3. Type css=div#divinthecenter *:nth-child(3).This will find the same as xpath=//div[@class='leftdiv']/input[2].

  4. Click on the Find button.

What just happened?

Unfortunately Selenium does not support the :nth-of-type pseudo class, so you will not be able to access the specific type. This pseudo class is extremely greedy in the way that it does look up over the page. It is also not available to the element selector library that is in use by Selenium. This is why the selector is using the wildcard * and then finding the nth- child from our starting div. The downside to using a selector in this manner is if any other node was placed in the way it would make the tests fail.

Finding an element by its inner text

Finding elements by their inner text can also be quite useful. In the XPath section of the book, we used the text() function to see the text it had. Earlier we had xpath=// div[contains(text(),'element has a ID')] to find a div with text in it. To update this XPath to a CSS Selector we would need to use the :contains pseudo class. This pseudo class is part of Sizzle which is used in Selenium IDE and Selenium RC. This will only work on browsers that do not have the CSS querySelector available. WebDriver delegates that task down to the browser if it can. I would recommend not using :contains if you plan on moving to Selenium WebDriver.

It is important to know that CSS selectors only have a read forward process. This means that you cannot find an element and then traverse backwards up the DOM. This is what makes CSS selectors a lot faster than XPath queries to find the same elements.

Pop quiz - using locators

  1. What is the most common way to find an element on a page?

    1. ID

    2. XPath

    3. CSS Selector

    4. Name

  2. If you wanted to find the sibling input that is after an input in the DOM, what would the XPath look like?

  3. What would the CSS look like for the previous question?

Have a go hero - working against Google Maps

Now that you have managed to create tests with different locators, try working against Google Maps. It is an extremely good site to work with XPath and CSS as it never has IDs or Names.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Selenium Topics