Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 321
David Easley Avatar asked Aug 24 '11 18:08

David Easley


2 Answers

Based on ZzZ's answer I think the issue is that the queries you are trying are absolute instead of relative. By using a starting / you force absolute search. Instead use the tag name as ZzZ suggested, ./ or .//.

Look in the XPath docs under "Location Path Expression"

like image 141
Adam Avatar answered Oct 02 '22 10:10

Adam


I also ran into this issue and spent quite a lot of time trying to figure out the workaround. And this is what I figured out:

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

Not sure why, but this works for me.

like image 31
ZzZ Avatar answered Oct 02 '22 08:10

ZzZ