简体   繁体   中英

How to use XPath in CasperJS' evaluate function

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM