1.下载PhantomJS到本地
下载地址:https://phantomjs.org/download.html
说明页:https://phantomjs.org/quick-start.html
2.准备文件
2.1 PhantomJS 用到的js文件内容,run.js
var page = require('webpage').create(),
system = require('system'),
address, output, size;
if (system.args.length < 3) {
phantom.exit(1);
} else {
address = system.args[1];//传入url地址
output = system.args[2];//输出图片的地址
page.viewportSize = { width: 800, height: 1800 };//自定义定义宽高
if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
size = system.args[3].split('*');
page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }
: { format: system.args[3], orientation: 'portrait', margin: '1cm' };
} else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
size = system.args[3].split('*');
if (size.length === 2) {
pageWidth = parseInt(size[0], 10);
pageHeight = parseInt(size[1], 10);
page.viewportSize = { width: pageWidth, height: pageHeight };
page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
} else {
console.log("size:", system.args[3]);
pageWidth = parseInt(system.args[3], 10);
pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
console.log ("pageHeight:",pageHeight);
page.viewportSize = { width: pageWidth, height: pageHeight };
}
}
if (system.args.length > 4) {
page.zoomFactor = system.args[4];
}
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
// -------开始---------获取指定div操作,如果需要获取全部的内容,删掉该段代码既可--------------------
var length = page.evaluate(function () {
//此函数在目标页面执行的,上下文环境非本phantomjs,所以不能用到这个js中其他变量
// 这里可以通过getElementsByClassName/getElementsById 来获取页面元素
var div = document.getElementsByClassName('main-content')[0]
var bc = div.getBoundingClientRect();
var top = bc.top;
var left = bc.left;
var width = bc.width;
var height = bc.height;
window.scrollTo(0, 10000);//滚动到底部
return [top, left, width, height];
});
//console.log(length);
page.clipRect = { //截图的偏移和宽高
top: length[0],
left: length[1],
width: length[2],
height: length[3]
};
// -------结束---------获取指定div操作,如果需要获取全部的内容,删掉该段代码既可--------------------
page.render(output);
phantom.exit();
}, 200);
}
});
// ----开始------解决页面出错时 PhantomJS 停止的问题---------
page.onError = function(msg, trace) {
conlog.log(msg)
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
};
// ----结束------解决页面出错时 PhantomJS 停止的问题---------
}
page.viewportSize = { width: 800, height: 1800 };//自定义定义宽高
3 调用
3.1 命令行方式调用
macos/linux 下调用方式:
把第二步的run.js放到第一步下载的文件解压后的bin目录下
执行: ./phantomjs run.js https://www.baidu.com/ test.png
既可将百度首页面截图放到 test.png 中
3.2 java方式调用
package net.sgjt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestPage2 {
private static String tempPath = "/Users/kangxuan/temp";// 图片保存目录
private static String BLANK = " ";
// 下面内容可以在配置文件中配置,这里要注意下 Macos/linux 下是 phantomjs,windows 下是 phantomjs.exe
private static String binPath = "/Users/kangxuan/Downloads/phantomjs-2.1.1-macosx/bin/phantomjs";// 插件引入地址
private static String jsPath = "/Users/kangxuan/Downloads/phantomjs-2.1.1-macosx/bin/run.js";// js引入地址
// 执行cmd命令
public static String cmd(String imgagePath, String url) {
return binPath + BLANK + jsPath + BLANK + url + BLANK + imgagePath;
}
//关闭命令
public static void close(Process process, BufferedReader bufferedReader) throws IOException {
if (bufferedReader != null) {
bufferedReader.close();
}
if (process != null) {
process.destroy();
process = null;
}
}
/**
* @param url
* @throws IOException
*/
public static void printUrlScreen2jpg(String url) throws IOException {
String imgagePath = tempPath+"/"+System.currentTimeMillis()+".png";//图片路径
//Java中使用Runtime和Process类运行外部程序
Process process = Runtime.getRuntime().exec(cmd(imgagePath,url));
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String tmp = "";
while ((tmp = reader.readLine()) != null) {
close(process,reader);
}
System.out.println("success");
}
public static void main(String[] args) throws IOException {
String url = "https://www.baidu.com/";//以百度网站首页为例
printUrlScreen2jpg(url);
}
}