我们可以在 casper.evaluate
函数中使用 document.querySelector
。但我找不到任何说明在评估函数中使用 XPath 选择器的文档。是否可以做同样的事情?如果是,那么如何?
最佳答案
基本上所有浏览器都通过 document.evaluate()
支持XPath 。 PhantomJS 也这样做(XPath 1.0)。
CasperJS提供了一些方便的函数来使用它。在页面上下文中( casper.evaluate()
内)有两个函数 __utils__.getElementByXPath(expression [, scope])
和 __utils__.getElementsByXPath(expression [, scope])
.
此示例打印第一个 <a>
的 href它发现具有 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"));
这与上面的示例类似,但不一样,因为元素属性和属性之间存在差异。
关于javascript - 如何在 CasperJS 的评估函数中使用 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34451055/