我有一个phantomJS脚本,其中包含以下内容:
page.open(url, function (status) {
if (status === "fail") { /* handle failure */ }
});
Run Code Online (Sandbox Code Playgroud)
状态检查有时会起作用,但即使请求返回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);
};
Run Code Online (Sandbox Code Playgroud)
因此,如果您需要检查第一个浏览器请求的状态(在这种情况下是google的html页面),您应该将其视为第一个返回的请求resources[0].status.在onResourceReceived处理程序中,您可以为尝试从中获取http代码的资源添加更多过滤器.
更新:感谢@fotijr,添加了对已完成回复的检查