node.js - 如何在 thenOpen 而不是未定义的 casper.js 中获取响应状态 404?

标签 node.js web-scraping phantomjs casperjs

知道为什么下面的代码没有在 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.

这是怎么回事!?

最佳答案

我刚刚运行了您的代码,它似乎可以很好地捕获 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');
    }
});

关于node.js - 如何在 thenOpen 而不是未定义的 casper.js 中获取响应状态 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18074093/

相关文章:

javascript - PhantomJS 和 Google Chrome/Firefox 的 HTML 输出不同

node.js - Puppeteer - Chrome |无法打开 X 显示器 | Ubuntu 20.04

mysql - Docker Compose 收到错误 ECONNREFUSED 127.0.0.1 :3306 with MySQL and NodeJS

python - 使用 BS4 抓取雅虎财经统计数据的网页

PHP 网页抓取

Python Selenium PhantomJS quit() 错误

javascript - 对 pug 中的所有页面使用通用布局

javascript - 使用 puppeteer 绕过 Headless Chrome 的验证码

r - 使用 R 进行网页抓取和循环浏览页面

linux - Karma/PhantomJS 在 Windows 上工作,在 Linux 上相同的配置无法向 PhantomJS 发送消息