One of the main factors in maintainable web testing is how good your element locators are. I’ve always used xpath since I’ve found it reliable and requiring very little maintenance (see this comment thread). But after playing with css locators for a bit (hello 21st century, sorry I’m late!) I’m a convert. Here’s a table to help you make the jump and join the cool kidz using css:
| XPath |
CSS equiv |
Explanation |
| //div |
div |
Find elements of a particular type |
id(‘bob’)
or
//*[@id='bob'] |
#bob |
Find elements with a specific ID |
| //div[@id='bob'] |
div#bob |
Find an elements of a particular type with a specific ID |
| //*[@class='bob'] |
.bob |
Find elements with a specific class |
| //div[@class='bob'] |
div.bob |
Find elements of a particular type with a specific class |
| //div//a |
div a |
Find descendant elements of a particular type |
| //div/a |
div > a |
Find direct child elements of a particular type |
| //a[@title] |
a[title] |
Find elements of a particular type that have a specific attribute |
| //a[@title='bob'] |
a[title="bob"] |
Find elements of a particular type that have an attribute of a specific value |
| //a[contains(@title,'bob')] |
a[title*="bob"] |
Find elements of a particular type that have an attribute that contains a specific value |
| //a[starts-with(@title,'bob')] |
a[title^="bob"] |
Find elements of a particular type that have an attribute that starts with a specific value |
Of course there’s more to it than that, but the above covers 95% of what I use on a day-to-day basis. It’s funny… looking at the table above it just struck me that css is to xpath what ruby is to java! CSS is more expressive and less noisy than XPath…
Things that XPath can do that CSS locators can’t:
- Get an element’s parent, eg: //div[@class='bob']/..
- You can get around this in watir by calling #parent on the element. Not sure about other tools