Pro:
- Allows you to back up through the DOM (e.g. "..")
- Allows you to match against CDATA in a tag (e.g. text())
Con:
- Typically slower than other locators on Internet Explorer
General rule for me is use By.id whenever possible. If I need css selectors or xpath to narrow match to one element, use css selector unless I must use xpath. Must use xpath if you need to find an element, back up through the DOM then down to the element you REALLY want or if I need to match against the visible text (e.g. text()).
For example,
<img src="google_button.gif" title="Google Button"/>
</a>
If I can guarantee the button has a tooltip "Google Button", which is visible to the user then a good locator would be: "//img[@title='Google Button']/.." This finds the image then goes up one level to the anchor. Another classic example of using xpath:
<div tabindex="0" role="button" class="GFUCT3GPN GFUCT3GFP GFUCT3GI5" id="b_post0" aria-pressed="false">
<input type="text" indextab="-1" style="opacity: 0; height: 1px; width: 1px; z-index: -1; overflow: hidden; position: absolute; ">
<span class="GFUCT3GDO">Post</span>
</div>
I know the 'button' will always have the text "Post" so I'd use the xpath, "//span[text()='Post']/../input". There is no way I can match against the text using css selectors.