使用phantomjs对网页截屏

      PhantomJS 是一个基于 WebKit 的服务器端 JavaScript API。它全面支持web而不需浏览器支持,其快速,原生支持各种Web标准: DOM 处理, CSS 选择器, JSON, Canvas, 和 SVG。 PhantomJS 可以用于 页面自动化 , 网络监测 , 网页截屏 ,以及 无界面测试 等。

开始

1、下载phantomjs

http://phantomjs.org/download.html中下载phantomjs,我这里是在window系统下面操作的,所以我这里就下载第一个window版本。有时候这个网站下载不了,下面我上传了一个附件,如果官网能下载就用官网下载的吧。

我上传附件的地址:https://download.csdn.net/download/liguoqingxjxcc/10591612

2、下载完成之后,我这边放在E盘的,解压到当前文件夹,我这里的路径就是E:\phantomjs-2.1.1-windows。把路径E:\phantomjs-2.1.1-windows\bin添加至环境变量path里面。在cmd命令行中使用phantomjs --version能看见版本号,就表示设置成功了。

3、在cmd命令中使用phantomjs E:/phantomjs-2.1.1-windows/examples/hello.js 就可以看见Hello, world!表示可以使用了。

4、如果我们想在java里面种使用,直接通过Process执行cmd命令就行了,请看下面例子

    public static void main(String[] args){  
        String url = "http://news.baidu.com";
        String saveImgPath = "C:\\Users\\Administrator\\Desktop\\百度新闻.png";
         
        String path = "E:/phantomjs-2.1.1-windows/";
        Runtime rt = Runtime.getRuntime();  
        try {  
            Process p = rt.exec(path + "/bin/phantomjs.exe "+ path +"examples/rasterize.js " + url.trim() + " " + saveImgPath ); 
            p.waitFor();
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }

  rasterize.js

"use strict";
var page = require('webpage').create(),
    system = require('system'),
    address, output, size;

    address = system.args[1];//需要截图的地址
    output = system.args[2];//截图保存位置
	page.viewportSize = { width: 1360, height: 600 };
    page.open(address, function (status) {
		if (system.args.length > 3 ) {//截图的宽高
			console.log("three param!");
			size = system.args[3].split('*');
			if (size.length === 2) {
				page.viewportSize = { width: size[0], height: size[1]};
				page.clipRect = { top: 0, left: 0, width: size[0], height: size[1] };//从什么地方开始截图、到什么地方结束
			}
		}else {
			// 通过在页面上执行脚本获取页面的渲染高度
			var bb = page.evaluate(function () { 
				return document.getElementsByTagName('html')[0].getBoundingClientRect(); 
			});
			// 按照实际页面的高度,设定渲染的宽高
			page.viewportSize = { width: bb.width, height: bb.height};
			page.clipRect = {
				top:    bb.top,
				left:   bb.left,
				width:  bb.width,
				height: bb.height
			};
		}
	
		
		if (system.args.length > 4) {//截图比例
			console.log("four param!bili:" + system.args[4]);
			page.zoomFactor = system.args[4];
		}
		
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit(1);
        } else {
            window.setTimeout(function () {
                page.render(output);
                phantom.exit();
            }, 5000);
        }
    });

结束

猜你喜欢

转载自blog.csdn.net/liguoqingxjxcc/article/details/81512861