Casper JS: TypeError: 'null' is not an object

Casper JS: TypeError: 'null' is not an object

我正在尝试获取此页面上的 "David Welsh" 文本:http://foster.uw.edu/faculty-research/directory/david-welsh/

当我在浏览器控制台中执行 document.getElementById('Boundless').children[0].children[2].children[0].children[1].children[0].innerHTML 时,我成功地 select 我想要的文本,但是当我 运行 我在终端中的 js 文件时,我收到错误:

TypeError: 'null' is not an object (evaluating 'document.getElementById('Boundless').children')

为什么这在我的浏览器中有效,但在我的本地 js 文件中无效?

casper.then(function(){
    this.each(links,function(self,link){
        self.thenOpen(link,function(a){
            this.echo(this.getCurrentUrl());
            var name = document.getElementById('Boundless').children[0].children[2].children[0].children[1].children[0].innerHTML;
                casper.echo(name);
            }
        });
    });
});

CasperJS 建立在具有两个上下文的 PhantomJS 之上。页面上下文 (casper.evaluate()) 已被沙盒化。这是访问DOM的唯一途径,您需要使用它。

var name = casper.evaluate(function(){
    return document.getElementById('Boundless').children[0].children[2].children[0].children[1].children[0].innerHTML;
});
casper.echo(name);

你想在其中使用的所有东西,你都必须显式传入。它无法访问外部定义的变量。

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!