无法获取与 CasperJS 的链接

Can't get links with CasperJS

我尝试 运行 这段代码并得到 "undefined"。有谁知道这段代码有什么问题吗?

var casper = require('casper').create();

casper.start('http://casperjs.org/', function() {
    this.echo(document.querySelector('a'));
});

casper.run();

CasperJS 建立在具有两个上下文的 PhantomJS 之上。内页上下文 casper.evaluate() 是沙盒化的,并且是唯一可以访问 DOM.

的上下文

DOM 节点无法传递到外部上下文,因此您需要 return 您可以使用的元素的某种表示形式:

this.echo(this.evaluate(function(){
    return document.querySelector('a').href;
}));

我建议您研究从中抽象出来的 CasperJS 函数,例如 getElementInfo() and getElementAttribute()

PhantomJS documentation 说:

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

如果没有明确说明,您无法从 Node 环境访问 DOM 功能。 CasperJS 具有 evaluate 函数:

var casper = require('casper').create();

casper.start('http://casperjs.org/', function() {
    this.echo(this.evaluate(function() {
        //we can now execute DOM functionality
        return document.querySelector('a').toString();
    }));
});

casper.run();