Skip to main content

Mar 13, 2010 - 1 minute read - Evil Tester Selenium

A simple getCSSCount for use with Selenium-RC

We know that XPath runs slowly in IE, but XPath has the getXPathCount method. And CSS runs quickly but Selenium doesn’t have a corresponding getCSSCount method.

I looked around for a simple way of getting count from a CSS selector.

I found this blog post by Aditya Ivaturi, but since I like to keep my Selenium setup and tests pretty simple, I wanted a much lower maintenance way of implementing the getCSSCount functionality.

So rather than amending the core in the jar file as Aditya did, or using user-extensions, I took the key JavaScript functionality presented in Aditya’s blog post and ran it with a get_eval.

Thus the following helper method:

private int getCSSCount(String aCSSLocator){ 
    String jsScript = 
	   "var cssMatches = eval_css(\"%s\", window.document);cssMatches.length;"; 
    return Integer.parseInt(
			       String.format(jsScript, aCSSLocator)));

Which you could use:

assertEquals(6, getCSSCount("*"));

This satisfied the itch I needed to scratch and it seems pretty low maintenance between Selenium versions.

You will need a Github account to comment. Or you can contact me with your comment.

I reserve the right to delete spam comments e.g. if your comment adds no value and its purpose is simply to create a backlink to another site offering training, or courses, etc.