Alex Rivera | Logout

Selenium 2 - Can findElement(By.xpath) be scoped to a particular element?

Asked 2011-08-24T18:14:10.367
14

All the examples of findElement(By.xpath) I've seen search the whole page, e.g.

WebElement td = driver.findElement(By.xpath("//td[3]"));

What I want to achieve is this:

WebElement tr = ... // find a particular table row (no problem here)
WebElement td = tr.findElement(By.xpath("/td[3]"));  // Doesn't work!

I've also tried other variations without luck: "td[3]", "child::td[3]"

Using "//td[3]" finds the first matching node in the whole page, i.e. not restricted to my tr. So it's looking like when you findElement by xpath, the WebElement on which you call findElement() counts for nothing.

Is it possible to scope findElement(By.xpath) to a particular WebElement?

(I'm using Chrome, in case it matters.)

PLEASE NOTE: By.xpath("//td[3]") is just an example. I'm not looking for alternative ways of achieving the same thing. The question is just about trying to ascertain whether foo.findElement() takes any notice of foo when used with a By.xpath selector.

Edit
Report

1 Answer

2

I think this might be a bug in the way that Selenium2 uses xpath. However, I believe I've successfully limited the scope using "::ancestor" before.

In any event, have you tried using Css Selectors to solve this? Is that an option for you? Try this:

tr.findElement(By.cssSelectors("td:nth-of-type(3)"));

This should do the job and is the equivalent of what you tried initially:

tr.findElement(By.xpath("//td[3]"));

answered 2011-09-08T21:49:06.293

Your Answer