硒2-findElement(By.xpath)可以限定于特定元素吗? [英] Selenium 2 - Can findElement(By.xpath) be scoped to a particular element?

查看:136
本文介绍了硒2-findElement(By.xpath)可以限定于特定元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过的所有findElement(By.xpath)示例都在整个页面中搜索,例如

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

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

我想实现的是这样:

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

我也尝试过其他没有运气的变体:"td [3]","child :: td [3]"

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

使用"//td [3]"查找整个页面中的第一个匹配节点,即不限于我的tr.因此,当您通过xpath查找element时,调用findElement()的WebElement毫无价值.

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.

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

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

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

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

请注意: By.xpath("//td [3]")只是一个示例.我不是在寻找实现同一目标的替代方法.问题仅在于尝试确定foo.findElement()与By.xpath选择器一起使用时是否注意到foo.

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.

推荐答案

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

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 .//.

在位置路径表达式"下找到 XPath文档

Look in the XPath docs under "Location Path Expression"

这篇关于硒2-findElement(By.xpath)可以限定于特定元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆