我是 casperjs 的新手,正在尝试使用它,但我无法使用它的 evaluate()
功能。
这是我的例子
var casper = require('casper').create();
casper.echo('started...');
casper.start('http://www.google.de/');
casper.then(function() {
this.echo(this.getTitle());
});
casper.then(function() {
this.evaluate(function() {
this.echo('test');
});
});
casper.run();
我正在用 casperjs sample.js
执行它
在 started...
和 Google
之后控制台输出没有任何反应。 evaluate方法中给定的闭包函数没有执行。
我什至无法通过控制台使用 --verbose
获得更多信息。
我做错了什么?
最佳答案
casper.evaluate
内部回调是页面上下文。其中的所有内容都直接在页面上执行,并且是沙盒化的。 this
引用此回调中的 window
对象。我怀疑谷歌是否添加了 window.echo
函数。所以你不会在控制台中看到任何东西。 this.echo
或 casper.echo
只能在页面上下文之外使用。
要真正从页面上下文中看到控制台消息,您需要注册到 remote.message
事件:
casper.on("remote.message", function(msg){
this.echo("remote.msg: " + msg);
});
然后向控制台写入一些内容:
this.evaluate(function() {
console.log('test');
});
如果你已经注册到 page.error
事件:
casper.on("page.error", function(pageErr){
this.echo("page.err: " + JSON.stringify(pageErr));
});
您会看到,window.echo
无法调用,因为它是 undefined
。调用它会导致 TypeError 停止执行 evaluate()
回调,然后返回 null
作为 evaluate()< 的结果
执行。
有关evaluate
的更多信息,请参阅我的回答 here .
注意:尝试在 google 上编写您的第一个脚本不是一个好主意,因为您会遇到多个问题。 Google 会嗅探用户代理,并会根据它为您提供不同的站点。还将考虑视口(viewport)大小。我建议您从 example.org 开始,然后是 stackoverflow.com,因为两者都运行良好。
关于javascript - 从评估方法调用时不会出现消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25135598/