Selenium:无法理解xPath

时间:2009-11-09 04:41:27

标签: html selenium screen-scraping automated-tests

我有一些像这样的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无效。有人能告诉我我在做什么错误吗?

2 个答案:

答案 0 :(得分:4)

您应该使用getAttribute来获取链接的href。您的XPath需要对最终节点的引用以及必需的属性。以下应该有效:

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

你也可以修改你的XPath,以便更灵活,甚至使用CSS来定位元素:

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

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

答案 1 :(得分:1)

我过去遇到过与Selenium和xpath类似的问题,无法真正解决它(除了更改表达式)。为了确保我建议用firefox的XPath Checker插件尝试你的xpath表达式。