美文网首页
CentOS 7下使用PhantomJS

CentOS 7下使用PhantomJS

作者: wuqingfeng | 来源:发表于2022-07-04 17:59 被阅读0次

安装解压

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 截图效果,效果很稳定。

相关文章

网友评论

      本文标题:CentOS 7下使用PhantomJS

      本文链接:https://www.haomeiwen.com/subject/tyudbrtx.html