0

I am new to PhantomJS and playing with the most basic code: fetching a google page and capture the screenshot.

The URL I'm trying to fetch is: https://www.google.com/#tbm=lcl&q=starbucks

If you open it in a real browser, you will see it looks like this:

enter image description here

But my PhantomJS it sees this:

enter image description here

At first, I thought maybe the async web content loading is too slow, so I managed to wait for many seconds and then capture the screen, but I see PhantomJS still fail to get the content.

Here's my code snippet:

var page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36';
page.viewportSize = { width: 1280, height: 800 };

page.open('https://www.google.com/#tbm=lcl&q=starbucks', function() {

  setTimeout(function(){
    page.render('screenshot_failed.png');
    phantom.exit();
  }, 5000);
});

Please point me what I may be missed when fetching this web page. Thanks!

Allan Jiang
  • 11,063
  • 27
  • 104
  • 165
  • did you try to set the viewport size? `page.viewportSize = { width: 480, height: 800 };` – quirimmo May 22 '17 at 18:29
  • Hi @quirimmo thanks for the comment. Yes I tried to set it to 1280x800, but it didn't help. (I will update the question to reflect this change.) – Allan Jiang May 22 '17 at 18:39
  • oh weird, can you try also another solution please? posting it as answer but I will delete it if it will not help. It's awful write or paste code here -.- – quirimmo May 22 '17 at 18:43

1 Answers1

1

In addition to all the code you already have, try to force the page to the size you want to inside the open callback:

var width = 1280;
var height = 800;
var webpage = require('webpage');

page.open('https://www.google.com/#tbm=lcl&q=starbucks', function(status) {
    page.evaluate(function(w, h) {
      document.body.style.width = w + "px";
      document.body.style.height = h + "px";
    }, width, height);
    page.clipRect = {top: 0, left: 0, width: width, height: height};                                                                                                                           
    page.render('screenshot_failed.png');
});
quirimmo
  • 9,800
  • 3
  • 30
  • 45