PhantomJS是一个无界面的,可脚本编程的WebKit浏览器引擎。它原生支持多种web 标准:DOM 操作,CSS选择器,JSON,Canvas 以及SVG。
PhantomJS下载地址:http://phantomjs.org/download.html
Js文件
// 导入webpage模块,创建一个实例
var page = require('webpage').create();
// 获取传入参数
var system = require('system');
// 浏览器可视区域大小
page.viewportSize = { width: system.args[2], height: system.args[3]};
// 裁切矩形的大小,前两个是基准点,后两个参数是宽高。
page.clipRect = { top: 0, left: 0, width: system.args[2], height: system.args[3]};
// 循环等待,条件满足出发截图
function waitFor(testFx, onReady, timeOutMillis) {
// 超时时间(默认超时60秒)
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 60000;
// 开始计时时间
var start = new Date().getTime();
// 出发截图条件
var condition = false;
// 循环定时器(每隔1秒判断一次)
var interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// 未超时但截图条件不满足
condition = page.evaluate(function() {
return document.getElementById('load_ok').value == 1;
});
} else {
if(!condition) {
// 超时且截图条件不满足退出
phantom.exit(1);
} else {
// 未超时且截图条件满足执行回调函数
onReady();
// 清除循环定时器
clearInterval(interval);
}
}
}, 1000);
};
// 截屏页面地址(根据需求自行修改)
var url = "http://127.0.0.1:8080/dbi/dataView/dashboard/preview.bs?id=" + system.args[1];
page.open(url,function(status){
// 检查页面是否加载完成
if (status !== "success") {
// 页面连接未找到
phantom.exit(-1);
} else {
// 判断截图条件
waitFor(function() {
// 获取截图条件初始值
return page.evaluate(function() {
return document.getElementById('load_ok').value == 1;
});
}, function() {
// 截图
page.render(system.args[4]);
// 退出
phantom.exit();
});
}
});
执行命令
// 命令格式(中间空格不可忽略):phantomjs目录 要执行的Js目录 参数1 参数2 ...
String str = "E:/phantomjs.exe E:/jietu.js " + dbId + " " + width + " " + height + " " + savePath;
Process pr = Runtime.getRuntime().exec(str);
// 等待截图处理完成,可不写
pr.waitFor();
// 页面截图状态(0正常 1超时 -1页面未找到 )
int state = pr.exitValue();
截图传入参数说明:dbId 页面查询ID width可视宽度与截屏宽度 height可视高度与截屏高度 savePath截屏图片保存路径