Attention: this was supposed to be a long-ish tutorial when it was first published. While it was in the process of being written PhantomJs was deprecated. Everybody and their mama are using puppeteer for all the tasks that other used PhantomJs for.
How to get the HTTP response code
of the page:
If you mainly used curl for troubleshooting, you actually will be surprised that HTTP response code is not readily available on PJS … although its not that hard to get either
console.log('---- Loading a web page -----'); var page = require('webpage').create(), url = 'http://mandog-test.ml/'; page.open(url, function (status) { console.log("Status: " + status); // This is not the status we are looking for console.log('---- Exiting ... ----'); phantom.exit(); }); page.onResourceReceived = function(response) { console.log(response.status); // This is the status we need };
$ ./phantomjs ../phantom_test.js ---- Loading a web page ----- 200 200 200 200 ---- Exiting ... ---- null
– What is that
null
– lets use --debug
flag to inspect more closely — any other flags?– Why is the response code returned multiple times and how to display it once accurately?
Other tasks:
- How to get the
all headers
(nicely formatted!) of the page: - How to get a
particular header
(bothkey
andvalue
) - How to execute a Javascript function.
didn’t know you don’t even need a browser anymore to use javascript 😱