Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render part of a page with PhantomJS?

Tags:

I would like to render individual HTML elements into PNGs using Phantom.JS. Does anyone know if this is possible? Also, how would I use Phantom.js to render a page that the user is already looking at?

like image 464
Dany Joumaa Avatar asked Aug 11 '12 19:08

Dany Joumaa


People also ask

How do I render part of a page?

To only render part of a page you need to set the clipRect attribute for the page and then render it. var clipRect = document. querySelector(selector). getBoundingClientRect(); page.

How do I run PhantomJS?

Go to the “bin” folder and check phantomjs.exe file. If you are using it on a Windows OS, then you can set the path variable under the environment variable for fast access through command prompt. The command to run the PhantomJS program: C:\> phantomjs [options] file.

What is PhantomJS browser?

PhantomJS is a headless browser, meaning a web browser without a graphical user interface, used for automating web page interaction. It is based on WebKit, the web browser engine. So it cannot render web pages but can act like a web browser.


Video Answer


2 Answers

To only render part of a page you need to set the clipRect attribute for the page and then render it.

var clipRect = document.querySelector(selector).getBoundingClientRect(); page.clipRect = {     top:    clipRect.top,     left:   clipRect.left,     width:  clipRect.width,     height: clipRect.height }; page.render('capture.png'); 

I don't understand the second part of your question. Phantom.js is headless meaning that there is no actual display that a user is looking at.

like image 161
jasonlfunk Avatar answered Nov 04 '22 02:11

jasonlfunk


Working example.

var page = require('webpage').create();  page.open('http://google.com', function() {   // being the actual size of the headless browser   page.viewportSize = { width: 1440, height: 900 };    var clipRect = page.evaluate(function(){     return document.querySelector('#hplogo').getBoundingClientRect();   });    page.clipRect = {     top:    clipRect.top,     left:   clipRect.left,     width:  clipRect.width,     height: clipRect.height   };    page.render('google.png');   phantom.exit(); }); 
like image 31
mgrachev Avatar answered Nov 04 '22 01:11

mgrachev