SpookyJ显示所有HTTP标头



我有一个网站,当我在传统浏览器中与之交互时,它的行为与诡异的/casper/phantom不同。我想通过将整个http头请求和响应打印到控制台或文件来进行调试,看看我的浏览器和幻影浏览器之间有什么不同(类似于我在浏览器上使用开发人员工具的方式)。如何在一个诡异的事件处理程序中获取包括标头在内的所有http请求/响应?

我通过SpookyJS从节点模块控制CasperJS-因此,根据Artjom B.的建议,我可以确定,在构建对象时,我只需要为传递到SpookyJS的CasperJS选项JSON添加一个事件侦听器。对于任何使用SpookyJS的人来说,该代码大致如下所示:

var Spooky = require( 'spooky' );
var spooky = new Spooky(
      {
        child: {
            'transport'         : 'http'
        },
        casper: {
            logLevel: 'debug'
          , verbose: true
          , onResourceRequested : function( C, requestData, request ){ this.emit('console', JSON.stringify( requestData ) ) }
          , onResourceReceived  : function( C, response ){ this.emit('console', JSON.stringify( response ) ) }
        }
      }, function ( err ) {
        if ( err ) {
            var e = new Error( 'Failed to initialize SpookyJS' );
            e.details = err;
            throw e;
        }
        spooky.start( "www.something.com" );
        spooky.run();
     }
);
spooky.on('console', function (line) {
   console.log(line);
});

在CasperJS中,您可以监听几个事件来提供更多信息。

casper.on('resource.requested', function(requestData, request) {
    this.echo('Request (#' + requestData.id + '): Headers' + JSON.stringify(requestData.headers, undefined, 4));
});

有关详细信息,请参见page.onResourceRequested


此外,为了了解发生了什么,您应该使用casper.capture()捕获尽可能多的屏幕截图

还有一些事件可以帮助您查看更多错误:

// http://docs.casperjs.org/en/latest/events-filters.html#remote-message
casper.on("remote.message", function(msg) {
    this.echo("Console: " + msg);
});
// http://docs.casperjs.org/en/latest/events-filters.html#page-error
casper.on("page.error", function(msg, trace) {
    this.echo("Error: " + msg);
    // maybe make it a little fancier with the code from the PhantomJS equivalent
});
// http://docs.casperjs.org/en/latest/events-filters.html#resource-error
casper.on("resource.error", function(resourceError) {
    this.echo("ResourceError: " + JSON.stringify(resourceError, undefined, 4));
});
// http://docs.casperjs.org/en/latest/events-filters.html#page-initialized
casper.on("page.initialized", function(page) {
    // CasperJS doesn't provide `onResourceTimeout`, so it must be set through 
    // the PhantomJS means. This is only possible when the page is initialized
    page.onResourceTimeout = function(request) {
        console.log('Response Timeout (#' + request.id + '): ' + JSON.stringify(request));
    };
});

最新更新