如何在thenOpen而非未定义的casper.js中获取响应状态404? [英] How to get response status 404 in casper.js within thenOpen instead of undefined?

查看:62
本文介绍了如何在thenOpen而非未定义的casper.js中获取响应状态404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Any idea why code below doesn't catch 404 in either response var or in the http.status.404 event?

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

I run this with phantomjs 1.9, casperjs 1.0.2 and 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.该怎么做?

Ideally I like to catch 404 within thenOpen(). How to do that?

更新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

I tried 404checker.js here 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()中捕获它,则可以执行以下操作:

I just ran your code and it seems to be working fine for catching the 404 error in the on event. If you want to catch it within the thneOpen(), something like this would work:

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.

Or you could use the response directly, response['status'] will be 404 in this case.

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

这篇关于如何在thenOpen而非未定义的casper.js中获取响应状态404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆