Create HTML Snapshot using Phantomjs

Posted By : Tarun Tyagi | 27-Mar-2016

Create HTML Snapshot Using PhantomJS

In this blog I will describe how you can create html snapshot using phantom js for seo your angular.js website

Step 1.First you need to setup phantom js

For linux operating system execute following commands.

cd /usr/local/share
sudo wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2
sudo tar xjf phantomjs-1.9.7-linux-x86_64.tar.bz2
sudo ln -s /usr/local/share/phantomjs-1.9.7-linux-x86_64/bin/phantomjs /usr/local/share/phantomjs
sudo ln -s /usr/local/share/phantomjs-1.9.7-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
sudo ln -s /usr/local/share/phantomjs-1.9.7-linux-x86_64/bin/phantomjs /usr/bin/phantomjs
 

For windows operating system
For downloading phantomjs CLICK HERE  

After downloading phantomjs-1.9.7-windows.zip unzip it and set the path of phantomjs.exe

For setting path

Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path in variable name or edit exist path variable -> write path of phantomjs.exe folder in variable value -> ok -> ok ->

Now open new command prompt and finally run this command for check version of phantom js

phantomjs -v

Step 2.Write script code for creating html snapshot

Open text editor and copy given code and save it with .js extension (for eg :- snapshot.js)

var page = require('webpage').create();
var fs = require('fs'),system = require('system'),address;
address=system.args[1];
page.open(address, function(status) {
   if(status === "success") {
       var result = page.evaluate(function(success) {
           Array.prototype.slice.call(document.getElementsByTagName("script")).filter(function(script) {
               return script.type != "application/ld+json";
           }).forEach(function(script) {
               script.parentNode.removeChild(script);
           });
           return document.documentElement.outerHTML;
       });
    fs.write(system.args[2],result, 'w');
   }
phantom.exit();
});

Now open your command prompt and run this command

phantomjs filelocation/filename.js websiteurl filelocation/#!/afterhasbangurl.html

For eg:- phantomjs e:\data\phantomjs\snapshot.js(insert that location where you save your js file) https://www.digitalcoinsexchange.com/#!/sell/bitcoin-Cash-USD-United-States-90(insert your website url ) e:data\#!\sell\bitcoin-Cash-USD-United-States-90.html(insert location where you want to store your html snapshot)

 

Thank for reading this blog

For more detail follow http://phantomjs.org/ link

 

About Author

Author Image
Tarun Tyagi

Tarun is a bright Java developer with experience in MEAN stack and Grails frameworks. Other than programming his area of interest are listening music and reading novels.

Request for Proposal

Name is required

Comment is required

Sending message..