31

为什么当我使用console.login时evaluate,它可以工作:

casper.then(function() {
  this.evaluate( function() {
    console.log('hello'); 
  });
});

但这不起作用:

casper.then(function() {
  this.evaluate( function() {
    setTimeout( function() {console.log('hello');}, 1000);
  });
});
4

4 回答 4

72

因为您混合了 casperjs 和远程页面环境。该evaluate函数将在远程页面环境中执行代码,因此console.log调用不会输出任何内容。

如果要捕获远程 console.log呼叫,请监听remote.message事件:

casper.on('remote.message', function(msg) {
    this.echo('remote message caught: ' + msg);
})

顺便说一句,事件文档非常详尽,评估文档也是如此。

于 2012-08-14T16:55:39.883 回答
19

@NiKo 的回答很关键。

我还建议添加以下内容,因为如果出现错误,您甚至可能无法打印出 console.log() 消息,而是以沉默告终。

casper.on( 'page.error', function (msg, trace) {
    this.echo( 'Error: ' + msg, 'ERROR' );
});
于 2013-08-22T18:17:32.243 回答
11

CasperJS 包括ClientUtils,可以从远程页面使用它来轻松地登录到 casper 脚本的控制台:

__utils__.echo('This message is logged from the remote page to the CasperJS console');
于 2015-03-25T15:35:32.323 回答
5

基于@odigity 的回答,这使得 casperjs 死于更熟悉的错误/堆栈跟踪:

var util = require('util');

casper.on('page.error', function exitWithError(msg, stack) {
    stack = stack.reduce(function (accum, frame) {
        return accum + util.format('\tat %s (%s:%d)\n',
            frame.function || '<anonymous>',
            frame.file,
            frame.line
        );
    }, '');
    this.die(['Client-side error', msg, stack].join('\n'), 1);
});
于 2015-05-06T11:41:37.123 回答