【问题标题】:How to get response status 404 in casper.js within thenOpen instead of undefined?如何在thenOpen而不是未定义的casper.js中获取响应状态404?
【发布时间】:2013-08-06 07:27:09
【问题描述】:

知道为什么下面的代码在 response var 或 http.status.404 事件中都没有捕获 404 吗?

我使用 phantomjs 1.9、casperjs 1.0.2 和 Windows 7 运行它

var casper = require("casper").create(),
    utils = require('utils');

casper.start();

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function(response) {
  casper.capture('test.png');
  utils.dump(response);
});

casper.on('http.status.404', function(resource) {
  this.echo('wait, this url is 404: ' + resource.url);
});

casper.run(function() {
  console.log('End');
  casper.exit();
});

理想情况下,我喜欢在 thenOpen() 中捕获 404。该怎么做?

更新 1:

我试过了

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function(response) {
  casper.capture('test.png');
  utils.dump(response);

    if(this.status(false)['currentHTTPStatus'] === 404) {
        console.log('Error 404');
    } else {
        console.log('No Error 404');
    }

});

这是输出:

undefined
No Error 404
End

还是没意思。

更新 2:

我在这里尝试了 404checker.js https://gist.github.com/n1k0/4509789

casperjs 404.js http://www.google.com/sadfafsdgfsd

输出:

URI.js loaded
Starting
http://www.google.com/sadfafsdgfsd
http://www.google.com/sadfafsdgfsd is okay (HTTP 200)
1 new links found on http://www.google.com/sadfafsdgfsd
All done, 1 links checked.

那到底是怎么回事!?

【问题讨论】:

  • 而且我根本找不到response 回调的记录位置...dump(response) 目前提供了一个类似{ "data": null } 的对象。

标签: node.js web-scraping phantomjs casperjs


【解决方案1】:

我刚刚运行了您的代码,它似乎可以很好地捕捉 on 事件中的 404 错误。如果你想在 thneOpen() 中捕获它,这样的事情会起作用:

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function() {
    if(this.status(false)['currentHTTPStatus'] === 404) {
        console.log('Error 404');
    } else {
        console.log('No Error 404');
    }
});

或者你可以直接使用响应,在这种情况下 response['status'] 将是 404。

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function(response) {
    if(response['status'] === 404) {
        console.log('Error 404');
    } else {
        console.log('No Error 404');
    }
});

【讨论】:

  • 我刚刚尝试并更新了结果。由于某种原因仍然无法捕获 404。 responseundefined
  • 这很奇怪,我不明白为什么它不起作用。今天我会争取一些时间来看看它并回复你。
  • 嗯,让我知道。我想知道Windows版本是否有bug!?
  • 这可能是一个 Windows 错误。我已经在两个版本的 Casper 上运行它,它在我的 OSX 机器上运行良好。 n1k0 的 404check.js 返回 ok,因为它只检查 404、500,而你是未定义的。 if (this.currentHTTPStatus === 404) { this.warn(link + ' is missing (HTTP 404)'); } else if (this.currentHTTPStatus === 500) { this.warn(link + ' is broken (HTTP 500)'); } else { this.echo(link + f(' 没问题 (HTTP %s)', this.currentHTTPStatus)); }
  • 对不起,我帮不了你了,希望你能解决!
猜你喜欢
  • 2017-11-29
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 2014-12-30
  • 2019-06-27
  • 1970-01-01
  • 2019-06-05
  • 2011-10-17
相关资源
最近更新 更多