How can I see the HTTP status code from the reques

2019-03-29 01:00发布

问题:

I have a phantomJS script that contains the following:

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

The status check works sometimes, but the status will still be "success" even if the request returns 500. How can I get the actual request status code?

回答1:

You can do it something like this:

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);
};

So, if you need to check the status of the first browser's request (in this case google's html page) you should see it as the first one returned in resources[0].status. In onResourceReceived handler you can add more filters for resources you try to get http code from.

UPDATE: thanks to @fotijr, added a check for completed responses



回答2:

In

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

resources variable is undefined,

even if I set it with

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


标签: phantomjs