java爬虫抓取网页数据(parserparser )
优采云 发布时间: 2021-10-17 07:22java爬虫抓取网页数据(parserparser
)
问题:
一些网页数据是由js动态生成的。一般我们通过抓包就可以看到真正的数据实体是哪个异步请求获取的,但是获取数据的请求链接也可能是其他js生成的。这时候我们希望直接拿到js加载后的最终网页数据。
解决方案:
幻象
1.下载phantomjs,【官网】:
2.我们是windows平台,解压,bin目录下会看到exe可执行文件。就够了。
3.写一个parser.js:
system = require('system')
address = system.args[1];
var page = require('webpage').create();
var url = address;
page.settings.resourceTimeout = 1000*10; // 10 seconds
page.onResourceTimeout = function(e) {
console.log(page.content);
phantom.exit(1);
};
page.open(url, function (status) {
//Page is loaded!
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
4.java 调用
Runtime rt = Runtime.getRuntime();
Process process = null;
try {
process = rt.exec("C:/phantomjs.exe C:/parser.js " +url);
InputStream in = process.getInputStream();
InputStreamReader reader = new InputStreamReader(in, "UTF-8");
BufferedReader br = new BufferedReader(reader);
StringBuffer sbf = new StringBuffer();
String tmp = "";
while ((tmp = br.readLine()) != null) {
sbf.append(tmp);
}
return sbf.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;