Help With XPath

If you need to find an element in your pages using Selenium, you can often use id= or name=. However, as your test cases get more complicated, learning a bit of XPath is unavoidable. Using XPath, you can express locations like "The first div under the table with id=main" or "The submit button in the form with class=login". Caveat: I am not an XPath expert, just working on getting it to work for crossplatform testing with Selenium..

Resources

Help With XPath
The XPath 1.0 spec from W3C (SS 2.5 is a good place to start if you want to know a few basic queries)
W3Schools XPath Tutorial
The Selenium Reference (includes examples throughout)
XPath Check extension (simpler, but less powerful)
XPath Tutorial at Zvon (excellent, with links to interactive XLab utility so you can practice)
FirePath FireBug extension (also has CSS3 and JQuery selectors)

Using XPath in Selenium

Most of these resources concentrate on XPath as used as a tool for generic XML work--fortunately using XPath against [X]HTML limits its scope a bit.

How the $%^@$ do I locate an element?

  1. Selenium supports many different locator types. Use the "xpath=" prefix for XPath locators, except where "xpath" is already in the method name.
  2. Use one of the Firefox extensions above and right click on the element in question, paste into the second argument of you script. Drawback: The resulting paths can be brittle (a fully qualified path like /html/body/div[1]/div[5]/div/table/tbody/tr/td/p/a[3] will break if any elements are added in the tree before the third a, and different browsers may insert things like tbody's in different places)
  3. Try to include id's in your code an work relative to them
  4. If you can't get an id, try selecting a class unique to given page ('contentheading' etc) and work from there: //div[@class='contentheading']/span[1]

Gotchas

  1. Set selectors [1] [2] etc are numbered from 1, not 0
  2. If you use multiple classes on an element (e.g. <div class="foo bar">) you can use //div[contains(@class, "foo")] to find matching elements.
  3. Don't forget that id's can't start with numbers.
  4. Don't forget that <a> elements have name's not id's.

Why wont this @#$%! XPath work in IE6?!

  1. for some reason the XPath expression id('foo')/span doesn't work in IE6. Try: //div[@id='foo']/span instead.
  2. //div[5][@class="foo"] (select the fifth div with class foo that occurs in the document tree) doesn't work in IE6. Try /descendant::div[@class="foo"][5] instead.

Before reporting problems with XPath to the dev team.

Try it out in Firebug, or Brian Slesinsky's XPath checker

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.