Selenium:无法理解 xPath
我有一些像这样的 HTML:
<h4 class="box_header clearfix">
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</span>
<small>
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</span>
</h4>
我正在尝试使用 Selenium 在 Java 中获取 href。我尝试过以下方法:
selenium.getText("xpath=/descendant::h4[@class='box_header clearfix']/");
selenium.getAttribute("xpath=/descendant::h4[@class='box_header clearfix']/");
但这些都不起作用。它一直抱怨我的 xpath 无效。有人可以告诉我我犯了什么错误吗?
I have some HTML like this:
<h4 class="box_header clearfix">
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</span>
<small>
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</span>
</h4>
I am trying to get the href here in Java using Selenium. I have tried the following:
selenium.getText("xpath=/descendant::h4[@class='box_header clearfix']/");
selenium.getAttribute("xpath=/descendant::h4[@class='box_header clearfix']/");
But none of these work. It keeps complaining that my xpath is invalid. Can someone tell me what mistake I am doing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 getAttribute 来获取链接的 href。您的 XPath 需要对最终节点的引用以及必需的属性。以下内容应该可行:
您还可以修改 XPath,以便更灵活地更改,甚至使用 CSS 来定位元素:
You should use getAttribute to get the href of the link. Your XPath needs a reference to the final node, plus the required attribute. The following should work:
You could also modify your XPath so that it's a bit more flexible to change, or even use CSS to locate the element:
我过去在使用 Selenium 和 xpath 时遇到过类似的问题,但无法真正解决它(除了更改表达式)。为了确保安全,我建议使用 XPath 检查器尝试使用 xpath 表达式火狐浏览器的插件。
I had similar problems with Selenium and xpath in the past and couldn't really resolve it (other than changing the expression). Just to be sure I suggest trying your xpath expressions with the XPath Checker addon for firefox.