微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个phantomJS脚本,其中包含以下内容
page.open(url,function (status) {
    if (status === "fail") { /* handle failure */ }
});

状态检查有时会起作用,但即使请求返回500,状态仍将是“成功”.如何获取实际的请求状态代码

解决方法

你可以这样做:
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页面),您应该将其视为资源[0] .status中返回的第一个请求.在onResourceReceived处理程序中,您可以为尝试从中获取http代码的资源添加更多过滤器.

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

原文地址:https://www.jb51.cc/js/240717.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐