Last night’s San Francisco Selenium Meetup was one of the two most useful I’ve attended (and I’ve attended quite a few!). Sauce Labs’ own Santiago Suarez Ordoñez gave a talk entitled CSS vs XPath Locators: An In-Depth Comparison & Why The Former Is the Way To Go.
Santi presented four reasons why we should all be using CSS locators instead of XPath locators whenever possible. CSS locators are (1) faster (on IE), (2) more readable, and (3) used by jQuery, whereas (4) “no one else uses XPATH.” I’m not sure he’s totally right about #2 and #4, but his evidence for #1 was quite compelling and amusing!
Santi presented a list of tools which one could use to help learn/use CSS locators. I was particularly intrigued by one he wrote himself: cssify.py. Here’s a copy/paste from my MacBook’s terminal window of cssify.py converting an XPath locator I used in an example elsewhere in this blog:
%mamp ./cssify.py "//select[@name='topnav']"
And here’s a little Perl program called convert.pl which I whipped up after the meeting in order to convert an entire HTML test case’s XPath locators into CSS ones. It calls Santi’s cssify.py program to do the conversion.
The “if” statement is admittedly ugly! The four sets of parentheses “memorize” the various components of a line like this:
Everything up through the opening <td> container gets “memorized” in $1. The XPath expression itself winds up in $3. Since the xpath= prefix for an XPath locator is optional, if it is present, it gets stored in $2 (but then never used). Finally, the closing </td> container goes into $4. And because the regular expression delimiter is a slash, all of the slashes in the regular expression had to be backslash-escaped.
The rest of the code is quite a bit easier to follow! Here’s a demo of what it does:
And although I didn’t show this in the demo, the foothill-converted.html test case does indeed run exactly the same as foothill.html.
Santi’s talk was supposedly a re-run of a popular one he gave at the Selenium Conference in April, but for reasons I don’t understand, it is not available via video along with the other talks on the Selenium Conference site. However, you can see his slide set now and the video of his talk will appear on the Sauce Labs blog in the near future (as is the case for all of the San Francisco Selenium Meet-Up presentations).
I’m a big believer at putting new info into action asap, so going forward, I hereby pledge to show only examples with CSS locators rather than XPath locators!