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 m understanding that u want to retrieve a particular td from a tr, so here's a snippet you can try it with your code to find 3rd td...
WebElement tr=//...find a particular table row
List<WebElement> columns = tr.findElements(By.tagName("td"));
Iterator<WebElement> j = columns.iterator();
int count=0;
while(j.hasNext())
{
WebElement column = j.next();
if(count==2)
{
System.out.print(column.getText());
}
count++;
}
You can change count value in if condition to retrieve another td..
Hope this will help you..
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]"));
WebElement td = tr.findElement(By.xpath("/td[3]"));
If you only want to to find the child elements of the tr use a relative path not an absolute.
This should work:
int index = 3;
List<WebElement> tds = tr.findElements(By.xpath(".//td"));
System.out.println(tds[index].getText());
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.
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"