如何从page.open请求中查看HTTP状态代码?

时间:2015-05-13 17:07:35

标签: phantomjs

我有一个包含以下内容的phantomJS脚本:

page.open(url, function (status) {
    if (status === "fail") { /* handle failure */ }
});

状态检查有时会起作用,但状态仍然是"成功"即使请求返回500.我如何获得实际的请求状态代码?

2 个答案:

答案 0 :(得分:8)

你可以这样做:

var page = require('webpage').create(),
    system = require('system'),
    resources = [];

page.open('http://google.com', function (status) {
    console.log('Loaded with http status:', resources[0].status);
    phantom.exit();
});

page.onResourceReceived = function(response) {
    // check if the resource is done downloading 
    if (response.stage !== "end") return;
    // apply resource filter if needed:
    if (response.headers.filter(function(header) {
        if (header.name == 'Content-Type' && header.value.indexOf('text/html') == 0) {
            return true;
        }
        return false;
    }).length > 0)
        resources.push(response);
};

因此,如果您需要检查第一个浏览器请求的状态(在这种情况下是google的html页面),您应该将其视为resources[0].status中返回的第一个请求。在 onResourceReceived 处理程序中,您可以为尝试从中获取http代码的资源添加更多过滤器。

更新:感谢@fotijr,添加了对已完成回复的检查

答案 1 :(得分:0)

page.property('onResourceError', function(res) {

资源变量未定义,

即使我用

设置它
var page = require('webpage').create(),
system = require('system'),
resources = [];