Selenium 2 - 可以将findElement(By.xpath)限定为特定元素吗?

Dav*_*ley 13 selenium selenium-webdriver

我看到的findElement(By.xpath)的所有例子都在搜索整个页面,例如

WebElement td = driver.findElement(By.xpath("//td[3]"));
Run Code Online (Sandbox Code Playgroud)

我想要实现的是:

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

我还尝试了其他变种而没有运气:"td [3]","child :: td [3]"

使用"// td [3]"查找整个页面中的第一个匹配节点,即不限于我的tr.所以看起来就像当你通过xpath找到元素时,你调用findElement()的WebElement一无所获.

是否可以将findElement(By.xpath)范围限定为特定的WebElement?

(我正在使用Chrome,以防万一.)

请注意: By.xpath("// td [3]")只是一个例子.我不是在寻找实现同样目标的替代方法.问题只是试图确定foo.findElement()在与By.xpath选择器一起使用时是否接受foo的任何通知.

Ada*_*dam 11

基于ZzZ的答案,我认为问题在于您尝试的查询是绝对的而不是相对的.通过使用启动/你强制绝对搜索.而是使用标签名称作为ZzZ建议,././/.

查看"位置路径表达式"下的XPath文档


小智 5

我也遇到了这个问题,并花了很多时间试图找出解决方法。这就是我想出的:

WebElement td = tr.findElement(By.xpath("td[3]"));
Run Code Online (Sandbox Code Playgroud)

不知道为什么,但这对我有用。

  • 由于没有前导斜杠(或两个),查询是相对的而不是绝对的。有关文档的链接,请参阅我的回答。 (2认同)

小智 0

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..
Run Code Online (Sandbox Code Playgroud)