首页  >  问答  >  正文

javascript - 如何在casperjs的evaluate函数中输出log

casperjs的evaluate函数中使用casper.log就无法输出,代码如下

var casper = require('casper').create({
    'verbose': true,
    'logLevel': 'debug'
});

casper.start('http://www.baidu.com/', function() {
    this.evaluate(function() {
        this.log('asd', 'error'); // 这一条无法输出
    });
}); 

大概的原因我也知道,应该是evaluate中的东西相当于在一个sandbox中执行,要与外界交互是只能通过特定的接口的

但这样造成我写程序的不便,因为在evaluate函数中就可能发生一些不可预期的情况,而我想把它log下来

我目前有两种解决方案

  1. evaluate函数返回时添加一个errorCode,从而判断发生了什么错误或者warning
  2. evaluate中使用console.log,并在外面监听remote.message,但这样等于多了一个日志流出来,也是十分不便

第二种解决方法的代码

casper.start('http://www.baidu.com/', function() {
    this.evaluate(function() {
        console.log('asd');
    });
}); 

casper.on('remote.message', function(msg) {
    this.log(msg, 'info');
});

所以有什么更好的解决方案吗?

大家讲道理大家讲道理2721 天前685

全部回复(2)我来回复

  • PHP中文网

    PHP中文网2017-04-10 14:37:34

    大概看了下 casper 的文件,evaluation 应该是在你打开的页面上执行函数,所以里面的代码貌似应该像是在写页面代码那样吧。

    我看示例是写的代码用于登录,所以尝试了一下这段

    var casper = require('casper').create({
        'verbose': true,
        'logLevel': 'debug'
    });
    
    casper.start('http://www.baidu.com/', function() {
        this.log("start http://www.baidu.com")
        this.evaluate(function() {
            alert("hello world")
        });
    });
    
    casper.run();
    

    输出的内容中有一句:

    [info] [remote] [alert] hello world
    

    在页面上调用 casper 的东西不太可能,this.log 应该等同于 window.log,是个不存在的函数,理论上来说 console.log 应该可以执行,但是没有反馈,也不晓得执行没得。

    回复
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 14:37:34

    通过测试发现有三种方案

    壹 console记录的日志,会和页面本身的console信息混合输出

    
        casper.on('remote.message', function(msg) {
          this.log(msg, 'info');
        });
        casper.open('http://www.baidu.com/', function() {
          this.evaluate(function() {
            console.log('from console.log');
          });
        });

    贰 alert记录的日志

        casper.start('http://www.baidu.com/', function() {
          this.log("start http://www.baidu.com")
        
          this.on('remote.alert',function(msg){
            this.echo('alert message:' + msg);
          });
        
          this.evaluate(function() {
            alert("hello world")
          });
        
        });

    叁 [推荐] 官方实例

        casper.start('http://www.google.fr/', function() {
            this.echo('Page title is: ' + this.evaluate(function() {
                return document.title;
            }), 'INFO'); // Will be printed in green on the console
        });

    回复
    0
  • 取消回复