Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phantomjs - take screenshot of a web page

Tags:

I have a URL (for e.g. http://www.example.com/OtterBox-77-24444-Commuter-Series-Optimus/dp/B00A21KPEI/ref=pd_sim_cps_4) and want to take a screenshot of it and preview it on my web page. Meaning, the user clicks on the preview button and PhantomJS needs to preview the web page as PNG/JPEG

I'm ok with using any other open source too.

like image 400
Abhi Avatar asked Jun 19 '13 11:06

Abhi


People also ask

How do I take a screenshot of a whole web page Windows 10?

To take a full screen screenshot Windows, follow the steps below: Press and hold Ctrl + Alt together, then press PRTSC. Press and hold the left mouse button, then drag the mouse on the scrolling window to select the area. Release the mouse click, and an auto-scroll will happen slowly.


2 Answers

I am going to assume you have installed Phantomjs and have created an alias in your .bashrc or have updated your system path to call the Phantomjs binaries. If not, you need to peruse a few beginner tutorials: http://net.tutsplus.com/tutorials/javascript-ajax/testing-javascript-with-phantomjs/

Once you have that set up, you will need to write a simple javascript file that you will call in the terminal (or shell, if you are using Windows). I will provide a simple, example script below.

var WebPage = require('webpage'); page = WebPage.create(); page.open('http://google.com'); page.onLoadFinished = function() {    page.render('googleScreenShot' + '.png');    phantom.exit();} 

Then, save your js file. Open up your terminal or shell and run the following

phantomjs yourFile.js 

That's it. Check the directory where you called the js file and you should have a png file with a screen shot of your web page.

This is very simple and there are a lot of caveats to f-ing with phantomjs, but this is about as basic as I can make it. If you need other recipes for phantomjs, try looking at these example scripts: https://github.com/ariya/phantomjs/wiki/Examples

like image 113
cliffbarnes Avatar answered Sep 23 '22 18:09

cliffbarnes


The above answer is fine for basic usage but PhantomJS doesn't know if all AJAX requests have been loaded or not. I made url-to-image to help with this problem.

  1. npm install url-to-image
  2. Write screenshot.js

    var screenshot = require('url-to-image'); screenshot('http://google.com', 'google.png').done(function() {     console.log('http://google.com screenshot saved to google.png'); }); 
  3. Run script node screenshot.js
like image 40
Kimmo Avatar answered Sep 20 '22 18:09

Kimmo