TesterHQ - The Evil Tester Blog Aggregator

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

A simple getCSSCount for use with Selenium-RC

Original Blog Posting on [blog.eviltester.com]

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.