如何在 CasperJS 的求值函数中使用 XPath

How to use XPath in CasperJS' evaluate function

我们可以在casper.evaluate函数中使用document.querySelector。但是我找不到任何说明在求值函数中使用 XPath 选择器的文档。可以这样做吗?如果是,那又如何?

基本上所有浏览器都通过document.evaluate()支持XPath。 PhantomJS 也这样做(XPath 1.0)。

CasperJS 提供了一些方便的功能来使用它。在页面上下文中(在 casper.evaluate() 内)有两个函数 __utils__.getElementByXPath(expression [, scope]) and __utils__.getElementsByXPath(expression [, scope]).

此示例打印它找到的具有 href 属性的第一个 <a> 元素的 href:

casper.echo(casper.evaluate(function(){
    return __utils__.getElementByXPath("//a[@href]").href
}));

CasperJS 还通过辅助函数支持页面上下文之外的 XPath 表达式:

var x = require("casper").selectXPath;

使 大多数 CasperJS 函数能够使用 XPath 表达式而不是 CSS 选择器:

casper.echo(casper.getElementAttribute(x("//a[@href]"), "href"));

这个和上面的例子很像,但是不一样,因为元素属性和属性的区别。