本文介绍了硒:不能够理解的XPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些HTML这样的:

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>

我想使用Selenium在这里得到的href在Java中。我曾尝试以下内容:

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']/");

但是,这些工作。它使抱怨我的XPath是无效的。谁能告诉我我在做什么错误?

But none of these work. It keeps complaining that my xpath is invalid. Can someone tell me what mistake I am doing?

推荐答案

您应该使用的getAttribute来获取链接的href。你的XPath需要的最后一个节点,加上必要的属性的引用。下面应该工作:

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:

selenium.getAttribute("xpath=/descendant::h4[@class='box_header clearfix']/a@href");

您也可以修改您的XPath,使其更灵活一些改变,甚至可以使用CSS来定位元素:

You could also modify your XPath so that it's a bit more flexible to change, or even use CSS to locate the element:

//modified xpath
selenium.getAttribute("//h4[contains(@class,'box_header')]/a@href");

//css locator
selenium.getAttribute("css=.box_header a@href");

这篇关于硒:不能够理解的XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:29