如果之前没用过phantomjs,先看看这个使用phantomjs操作DOM并对页面进行截图需要注意的几个问题
在windows cmd中执行:phantomjs.exe phantomtest.js http://127.0.0.1:8888/test/index/ test.png
第一个参数:js的路径;第二个参数:要截图的url;第三个参数:保存图片的路径
phantomtest.js代码如下:
var page = require('webpage').create();
page.onConsoleMessage = function (msg) {
console.log(msg);
}
system = require('system');
var url;
var path;
if (system.args.length == 1) {
phantom.exit();
}
else {
url = system.args[1];
if (system.args.length == 3) {
path = system.args[2];
} else {
path = "hello.png";
}
}
var width = 1349;
var height = 1883;
page.viewportSize = {width: width, height: height}; //浏览器大小,宽度根据网页情况自行设置,高度可以随意,因为后面会滚动到底部
page.open(url, function (status) {
if (status != "success") {
console.log('FAIL to load the address');
phantom.exit();
}
var length;
window.setTimeout(function () {
length = page.evaluate(function () {
//此函数在目标页面执行的,上下文环境非本phantomjs,所以不能用到这个js中其他变量
var div = document.getElementById('index_content'); //要截图的div的id
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]
};
}, 5000);
window.setTimeout(function () {
page.render(path);
phantom.exit();
}, 5000 + 500);
});
亲测echarts的图表是可以截出来的,不像我之前用的html2canvas(Echarts截出来是空的没有数据)