Reputation: 8224
We can use document.querySelector
in the casper.evaluate
function. But I could not find any documentation illustrating the use of XPath selectors inside the evaluate function. Is it possible to do the same? If yes, then how?
Upvotes: 1
Views: 962
Reputation: 61892
Basically all browsers support XPath through document.evaluate()
. PhantomJS does so too (XPath 1.0).
CasperJS provides some convenience functions to use it. In the page context (inside casper.evaluate()
) there are the two functions __utils__.getElementByXPath(expression [, scope])
and __utils__.getElementsByXPath(expression [, scope])
.
This example prints the href of the first <a>
element it finds that has a href
attribute:
casper.echo(casper.evaluate(function(){
return __utils__.getElementByXPath("//a[@href]").href
}));
CasperJS also supports XPath expressions outside of the page context with a helper function:
var x = require("casper").selectXPath;
which enables most CasperJS functions to use XPath expressions instead of CSS selectors:
casper.echo(casper.getElementAttribute(x("//a[@href]"), "href"));
This is similar, but not the same as the example above, because of the differences between element properties and attributes.
Upvotes: 1