某些系统的需求中,要求提供服务器端的部分网页截图或全部网页截图服务,博主最近也接到这样一个需求。
通过几天的学习推荐以下两个工具:Phantomjs及Slimerjs
1、Phantomjs
phantomjs是很多python爬虫及网页自动化测试使用的工具,采用webkit内核,完全的无界面浏览器工具,使用js进行各种操作,不支持flash组件。
2、slimerjs
slimerjs是与phantomjs功能上高度相似的工具 ,采用Gecko内核,不完全的无界面浏览器工具,主要体现在打开网页进行操作时会弹出slimerjs的浏览器窗口。同样使用js进行各种操作,支持多种组件,如flash。
相同点:
1、二者都是可用于网页自动化测试的工具
2、功能高度相似,Phantomjs使用的js脚本几乎完全适用于Slimerjs
3、均通过cmd/terminal调用自身exe或bat运行,即[cmd]C:\Users\***\Desktop\phantomjs-windows\phantomjs-2.1.1-windows\bin>phantomjs hello.js
不同点:
1、Phantomjs在新版本中将自身完全的封装在了exe中,不需要提供浏览器环境等,而slimerjs运行需要系统安装火狐浏览器,支持的多种组件也是基于安装过组件的火狐浏览器环境实现的。
2、由于部分原因(内核?)导致对同一个网页进行完全截图时结果稍有不同,如:隐藏的div在slimerjs截图中出现,在phantomjs截图中未出现。
3、phantomjs不支持如flash的多种组件,而slimerjs由于自身特性支持。
4、slimerjs截超长的网页会出现截图不完全的情况,而phantomjs不会出现。
样例JS:
var page = require('webpage').create(); //创建page实例
testindex = 0;
loadInProgress = false;
page.onLoadStarted = function() { //设置网页加载开始触发事件
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() { //设置加载结束触发事件
loadInProgress = false;
console.log("load finished");
};
page.viewportSize = { //设置窗口大小
width:1920,
height:1080
};
var steps = [
function() { //打开url
page.open("https://account.xiaomi.com/pass/serviceLogin");
},
function() {
page.evaluate(function(obj) {//evaluate即模拟在浏览器F12的console中进行对DOM的操作,注意,其中无法调用page等phantomjs/slimerjs对象
var form = document.getElementById("login-main-form");
form.elements["username"].value = '$USRNAME$';
form.elements["pwd"].value = '$PSW$';
form.elements['login-button'].click();
return document.title;
});
loadInProgress = true;
},
function() {
page.render('login-succ-xiaomi.png'); //截图
}
];
var interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
phantom.exit();
}
}, 5000);
phantomjs API地址:(网页左侧api树)http://phantomjs.org/api/webpage/property/cookies.html
slimerjs API参考Phantomjs