How can I see the HTTP status code from a request made using page.open?

I have a phantomJS script that contains the following:

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

Checking the status sometimes works, but the status will still be โ€œsuccessfulโ€, even if the request returns 500. How can I get the status code of the actual request?

+6
source share
2 answers

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 request (in this case on the google html page), you should see it as the first returned in resources[0].status . In the onResourceReceived handler, you can add additional filters for the resources from which you are trying to get the http code.

UPDATE: thanks to @fotijr added verification of completed responses

+7
source

IN

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

resource variable undefined,

even if I installed it using

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

Source: https://habr.com/ru/post/987149/


All Articles