安装解压
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
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
phantomjs -v
phantomjs -v
phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
#解决方案
yum install fontconfig freetype2
命令行截图
phantomjs render.js http://cnblogs.com cnblogs.png
其中render.js内容如下:
var page = require('webpage').create(),
system = require('system'),
address, output, size;
if (system.args.length < 3 || system.args.length > 5) {
console.log('Usage: rasterize.js URL filename');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 1024, height: 600 };
page.open(address, function (status) {
// 通过在页面上执行脚本获取页面的渲染高度
var bb = page.evaluate(function () {
return document.getElementsByTagName('html')[0].getBoundingClientRect();
});
// 按照实际页面的高度,设定渲染的宽高
page.clipRect = {
top: bb.top,
left: bb.left,
width: bb.width,
height: bb.height
};
// 预留一定的渲染时间
window.setTimeout(function () {
page.render(output);
page.close();
console.log('render ok');
}, 5000);
});
}
后记
PhantomJS是真难用,各种兼容性问题,已经不再更新。推荐使用google-chrome和chromedriver搭配使用,也可以达到headless 截图效果,效果很稳定。
网友评论