Wednesday, November 30, 2011

Selenium xpath arrays

Accessing xpath array elements in Selenium can be tricky! Sometimes you may have a number of elements on a page that can only be referenced with the same locator (for example, you can't rely on unique id's, only on some field they all have in common)

example:
a website has 4 buttons with 'addToCart' in onClick being the only reliable bit to check:

  ("//button[contains(@onclick,'addToCart')])

  you might think you could click on them by subscripting like this:
  sel.click("//button[contains(@onclick,'addToCart')][1]")
  sel.click("//button[contains(@onclick,'addToCart')][2]")

but no. the first one succeeds and fakes you into thinking you can access the array this way. but you can't. if you take out the [1] you get the same result. 

So what you have to do is isolate the array first, using the 'xpath=' notation, and then subscript it:

  sel.click("xpath=(//button[contains(@onclick,'addToCart')])[3]")

notice the use of 'xpath=' and the extra parens around the locator, followed by the subscript!

No comments:

Post a Comment