Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJS: specify User Agent when making a call

Tags:

phantomjs

I am using PhantomJS to make calls to a web page, like this:

page.open('http://example.com', function (s) {   console.log(page.content);   phantom.exit(); }); 

I am using this in the context of Drupal Simpletests, which require me to set a special USERAGENT in order to use the test database instead of the real database. I would like to fetch the web page a specific user agent. For example, in PHP with Curl, I can do this with CURLOPT_USERAGENT before making a cUrl call.

Thanks!

Albert

like image 718
alberto56 Avatar asked Oct 03 '13 12:10

alberto56


1 Answers

I found the answer in the useragent.js file in the phantomjs examples directory:

var page = require('webpage').create(); console.log('The default user agent is ' + page.settings.userAgent); page.settings.userAgent = 'SpecialAgent'; page.open('http://www.httpuseragent.org', function (status) {     if (status !== 'success') {         console.log('Unable to access network');     } else {         var ua = page.evaluate(function () {             return document.getElementById('myagent').innerText;         });         console.log(ua);     }     phantom.exit(); }); 
like image 150
alberto56 Avatar answered Oct 03 '22 12:10

alberto56