美文网首页PHP经验分享
php使用phantomjs截取网页截图

php使用phantomjs截取网页截图

作者: 旅行者xy | 来源:发表于2019-03-22 16:08 被阅读0次
  • 场景
    有一个视频播放地址,需要对该网页进行截图

  • 解决思路:
    1.将视频下载到本地,使用ffmpeg进行处理
    2.使用phantomjs,phantomjs内置了webkit浏览器引擎,phantomjs可以模拟浏览器打开视频地址,然后进行整个网页的截图。

WebKit 是一个开源的浏览器引擎,与之相对应的引擎有Gecko(Mozilla Firefox 等使用)和Trident(也称MSHTML,IE 使用)

  • 选择
    第一个方案,ffmpeg只能处理本地视频或者处理RTCP直播流,同时要求的视频直播地址中有部分是直播流,有部分是组件渲染,所以该方案不可行。
    因此选择第二个方案。

  • phantomjs进行网页截图,这里以window平台为例
    1.首先,去phantomjs官网下载页面下载phantomjs程序,支持window、mac os、linux、freebsd平台。
    2.将下载下来的phantomjs添加系统环境变量里
    3.编写js文件capture.js

"use strict";  //严格模式

var page = require('webpage').create();
var system = require('system');
page.viewportSize = {
    width : 1024,
    height : 720
};

if (system.args.length < 3) {
    console.log('param must greater 2');
    phantom.exit();
} else{
    var url = system.args[1];  //远程视频地址
    var saveFile = system.args[2];  //保存截图的文件路径
    page.open(url, function(status) {
        if (status == 'success'){
            // 通过在JS获取页面的渲染高度
            var rect = page.evaluate(function () {
              return document.getElementsByTagName('html')[0].getBoundingClientRect();
            });
            // 按照实际页面的高度,设定渲染的宽高
            page.clipRect = {
              top:    rect.top,
              left:   rect.left,
              width:  rect.width,
              height: rect.height
            };
            setTimeout(function() {
                var result = page.render(saveFile);
                page.close();
                console.log(result);
                phantom.exit();
            }, 1000);  //延迟截图时间
        }
    })
}
  1. 在php中进行调用
$url = 'http://xxx';
$savePath = 'c:\test.png';
$jsPath = 'c:\phantomjs.js';
$command = "phantomjs {$jsPath}  {$url}  {$savePath}";
$result = @exec($command );

这样就对网页进行截图,保存截图在指定路径中。

另外:有大神在github上提交了个操作phantomjs的php类库,可以参考使用:

https://github.com/jonnnnyw/php-phantomjs
http://jonnnnyw.github.io/php-phantomjs/4.0/2-installation/

参考:
http://phantomjs.org/download.html
http://phantomjs.org/api/webpage/method/render.html

相关文章

网友评论

    本文标题:php使用phantomjs截取网页截图

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