需求:截取可访问URL网页为图片,可以把HTML中指定的dom截取成图片,并且替换原有的dom为标签。
技术选型:主要完成功能如下:
可以按照选择器方式截取html中的dom保存为图片。
可以替换html中的dom节点
可以把替换后的html片段保存为本地文件。
实现技术方案:java + phantomjs + casperjs
安装环境
windows系统安装:
phantomjs:
环境变量配置:
验证安装:
casperjs 安装与phantomjs一样。
在Linux中安装:
例如:phantomjs 放在路径 /usr/local/phantomjs
然后,执行命令:
ln -s /usr/local/phantomjs/bin/phantomjs /usr/local/bin/phantomjs
验证安装命令:
phantomjs -v
casperjs安装类似,但是注意casperjs 查看版本命令是: casperjs --version
casperjs 脚本文件
var fs = require('fs');var casper = require('casper').create({
clientScripts: ["jquery.js"]
});var args =casper.cli.args;var url = args[0];var fileName = args[1];var filePath = args[2];var imgPath = args[3];var imgAccessPath = args[4];
casper.start(url, function() {
});
casper.then(function() {var _tharray = this.evaluate(function() {//evaluate 相当于向模拟浏览器中添加需要执行的js函数
var _styleObjAy = $("section[widget-type=style]");var _array = newArray();for (var index = 0; index < _styleObjAy.length; index++) {var element =_styleObjAy[index];
$(element).parent().addClass("casper-th-" +index);
_array.push("casper-th-" +index);
}return_array;
});//this.echo("返回结果:" + _tharray);//截图
for (var index = 0; index < _tharray.length; index++) {//console.log(_tharray[index]);
this.captureSelector(imgPath + '/' + _tharray[index] + '.png', "section[class*=" + _tharray[index] + "]");
}
});
casper.thenEvaluate(function(imgAccessPath) {//自由布局组件
var _casperTH = $("section[class*=casper-th-]");for (var index = 0; index < _casperTH.length; index++) {
$(_casperTH[index]).replaceWith("");
}//图片组件
var _imgRapl = $("section[widget-type=image]");var_imgObj;var_imgsrc;for (var _index = 0; _index < _imgRapl.length; _index++) {
_imgObj= $(_imgRapl[_index]).find("section[build-od=image]").css("background-image");if (typeof (_imgObj) != 'undefined') {
_imgsrc= _imgObj.substring(4, _imgObj.length - 1);
$(_imgRapl[_index]).parent().replaceWith("");
}
}
}, imgAccessPath);
casper.then(function() {//输出html文件
fs.write(filePath + '/' + fileName + '.html', this.getHTML("#section-base"), 'w'); //html写文件
});
phantom.outputEncoding= "gbk";
casper.run();
代码注释:
var casper = require('casper').create({
clientScripts: ["jquery.js"]
});
其中引用了jquery文件,需要放在casperjs/bin 目录下,如下图:
var url = args[0];var fileName = args[1];var filePath = args[2];var imgPath = args[3];var imgAccessPath = args[4];
cmd 中传递的各种参数
var _tharray = this.evaluate(function() {//evaluate 相当于向模拟浏览器中添加需要执行的js函数
var _styleObjAy = $("section[widget-type=style]");var _array = newArray();for (var index = 0; index < _styleObjAy.length; index++) {var element =_styleObjAy[index];
$(element).parent().addClass("casper-th-" +index);
_array.push("casper-th-" +index);
}return_array;
});
其中 evaluate 相当于向模拟浏览器中添加需要执行的js函数,后面的thenEvaluate函数类似功能。
casper.then(function() {//输出html文件
fs.write(filePath + '/' + fileName + '.html', this.getHTML("#section-base"), 'w'); //html写文件
});
输出文件,其中this.getHTML()函数可以获取html判断。
Java中执行方式:
public classDynamicDownLoadTest {public staticString getSrcContent(String urls){//windows下casperjs位置
String casperPath = "G:/study/screeshot/node_modules/casperjs/bin/";
String imgRelativePath= "static";
String worksAbsolutePath= "D:/workspace/myeclipse2014/article/src/main/webapp/opusres/D38BDD5EAC2F42BD91ADFCFD58FA7B20";
String worksId= "D38BDD5EAC2F42BD91ADFCFD58FA7B20";
String worksAccessPath= "http://onepage.loudcloud.cn/article/opusres";
String url= "http://onepage.loudcloud.cn/article/opusres/15E6D5D4E8EE490A88434DC432A70FA3/index.html";
String scriptFile= "G:/study/screeshot/casperjsReplaceStyle.js";
String htmlName= "index-wx";
Runtime rt=Runtime.getRuntime();
Process process= null;
String cmd= casperPath + "casperjs.exe"+scriptFile+" "+url+ " "+ htmlName +" "+ worksAbsolutePath +" "+ worksAbsolutePath +"/"+imgRelativePath +" "+ worksAccessPath+"/"+imgRelativePath;try{
process=rt.exec(cmd);
}catch(IOException e) {//TODO 这里写异常处理的代码
e.printStackTrace();
}
InputStreamis =process.getInputStream();
BufferedReader br= new BufferedReader(new InputStreamReader(is));
StringBuffer sbf= newStringBuffer();
String tmp= "";try{while((tmp = br.readLine())!=null){
sbf.append(tmp);
}
}catch(IOException e) {//TODO 这里写异常处理的代码
e.printStackTrace();
}returnsbf.toString();
}public static voidmain(String[] args){
String src= DynamicDownLoadTest.getSrcContent("http://onepage.loudcloud.cn/article/opusres/15E6D5D4E8EE490A88434DC432A70FA3/index.html?t=0.5180855805519968");
System.out.println(src);
}
}
上述是在windows环境执行,如果在Linux环境下需要注意一下事项:
phantomjs 和casperjs 执行命令需要赋权,命令 chrom -R 777 phantomjs
Linux系统中没有需要渲染的字体,安装字体:创建 /usr/share/fonts/chinese/TrueType,把windows中C:\Windows\Fonts内的文件拷贝过去。