如何实现动态页面爬虫的java程序编写 java程序调用命令行执行phantomjs脚本返回源码为空
我首先下载了一个phantomjs,接下来完成了两个代码,一个是用phantomjs去获取页面(采用js编写行为),一个是采用java去调用phantomjs来达到获取内容的目的。
下面直接贴上我的代码,请各位大神帮帮忙!哪里出了问题。
//snap.js,获取页面代码的js代码。
var page = new WebPage(),
address, output, size;
var fs = require('fs');
page.settings.resourceTimeout = 5000; // 5 seconds
page.onResourceTimeout = function(e) {
console.log(e.errorCode); // it'll probably be 408
console.log(e.errorString); // it'll probably be 'Network timeout on resource'
console.log(e.url); // the url whose request timed out
phantom.exit(1);
};
if (phantom.args.length < 2 || phantom.args.length > 3) {
console.log('Usage: rasterize.js URL filename');
phantom.exit();
} else {
address = phantom.args[0];
output = phantom.args[1];
page.viewportSize = { width: 600, height: 600 };
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
//window.setTimeout(function () {
// page.render(output);
// phantom.exit();
//}, 200);
console.log("woca");
console.log(page.content);
phantom.exit();
/*try {
//sleep(5000);
fs.write(output, page.content, 'w');
phantom.exit();
} catch(e) {
console.log(e);
}
*/
}
});
} //估计好多人不怎么看懂上面代码,就是一个phantomjs渲染获取页面源代码的脚本
获取完之后,下面是一段java代码,通过调用phantomjs得到页面源代码,我做的实验用的网址url为腾讯滚动http://roll.news.qq.com
//爬动态网页(命令行调用phantomjs)
public static String crawDynamicPage(String sUrl,String sChset){
String sRet = "";
String sCharset = sChset;
try{
Runtime run = Runtime.getRuntime();
String str1 = "F:/PhantomJS/phantomjs-1.9.7-windows/phantomjs.exe snap.js ";
String cmd = str1 + sUrl; //后面要有输出
Process process = run.exec(cmd);
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
//System.out.println(line);
sb.append(line);
sb.append("/r/n");
}
sRet = sb.toString();
}
catch(IOException e) {
//
e.getMessage();
}
return sRet;
}
其实原理很简单,就是通过进程间通信用java调用phantomjs这个组件去请求渲染页面,不知道什么原因,最近调试sRet返回的字符串都是空,说明没有获取到页面内容,所以以为是timeout超时问题,就在js脚本上添加了超时timeout语句,也不知道添加的对不对,反正现在一直出不来内容,但是通过dos的命令行窗口可以调用phantomjs返回页面源码,请大神们支招!不胜感激!