centos7上安裝phantomjs並對頁面截屏

安裝
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
yum install bzip2
tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
mv phantomjs-2.1.1-linux-x86_64 /usr/local/src/phantomjs
ln -sf /usr/local/src/phantomjs/bin/phantomjs /usr/local/bin/phantomjs
yum install -y fontconfig freetype2
yum install -y bitmap-fonts bitmap-fonts-cjk
yum groupinstall "fonts" -y
fc-cache
phantomjs -v

 

測試1

創建一個文件:hello.js

console.log('Hello, world!');
phantom.exit();

運行:phantomjs hello.js

輸出:Hello, world!

 

測試2

創建一個文件:example.js

var page = require('webpage').create();
page.open('http://example.com', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    page.render('./example.png');
  }
  phantom.exit();
});

運行:phantomjs example.js

輸出圖片文件:./example.png

 

測試3

默認的截圖尺寸是400*300,這個太小了,可以指定瀏覽器可視區域尺寸。

var page = require('webpage').create();
var w = 1920;
var h = 792;
page.viewportSize = { width: w, height: h };
page.clipRect = { top: 0, left: 0, width: w, height: h };
page.open('http://example.com/', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    page.render('./example.png');
  }
  phantom.exit();
});

 

測試4

對於異步加載的頁面,需要等會待會才能截圖。

var page = require('webpage').create();
var w = 1920;
var h = 792;
page.viewportSize = { width: w, height: h };
page.clipRect = { top: 0, left: 0, width: w, height: h };
page.open('http://example.com', function() {
  console.log("Status: " + status);
  if(status === "success") {
    window.setTimeout(function () {
        page.render('./example.png');
        phantom.exit();
    }, 3000);
  } else {
    console.log('Unable to load the address!');
    phantom.exit(1);
  }
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章