java ec.exec exe_java 利用chrome+puppeteer实现爬虫

java在进行爬虫过程中会因为网站作出反爬措施,导致抓取的内容不全面,所以需要利用模拟浏览器,打开页面获取到页面的全部内容。本文以腾讯新闻https://news.qq.com/为例。

环境配置参考https://www.jianshu.com/p/6c3d90bef17f,可以配置nodejs的环境。

一、使用jsoup解析网页,当解析腾讯新闻时只能获取到网页的源码,其他与新闻相关的内容一概获取不到,从而无法抓取到有用的信息。

/**

* 利用jsoup解析网页

* @param url

* @return

*/

public static Document getDocumentByJsoup(String url){

Document document = null;

try {

document = Jsoup.connect(url).timeout(15000).get();

String text = document.getElementsByTag("body").text();

System.err.println(text);

} catch (IOException e) {

e.printStackTrace();

}

return document;

}

测试获取的结果,获取不到新闻列表

fcccd9221fbd

result.png

二、利用chrome + nodejs的方式进行测试。

/**

* 利用chrome方式获取页面信息

* @param url

* @return

*/

public static Document getDocument(String url){

Document document = null;

//chrome浏览器地址

String chromePath = "你的chrome浏览器根目录";

//nodejs地址 + 截图的js的地址(两个需要在同一个目录之下)

String nodeJSPath = "nodejs根目录地址 渲染页面所需要的js根目录地址.js";

String BLANK = " ";

String exec = nodeJSPath + BLANK + chromePath + BLANK + url;

try {

//执行脚本命令

Process process = Runtime.getRuntime().exec(exec);

System.err.println("ecec =======> " + exec);

InputStream is = process.getInputStream();

document = Jsoup.parse(is, "UTF-8", url);

try {

process.waitFor();

} catch (InterruptedException e) {

e.printStackTrace();

}

process.destroy();

process = null;

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return document;

}

运行获取到的结果

fcccd9221fbd

result2.png

而在任务执行过程中所需要的渲染页面的js

fcccd9221fbd

render.png

写好js后可以利用cdm进行测试。java中也可以利用相同的方法进行截图。只需要在程序中将js换掉就行。并增加一个参数

fcccd9221fbd

截图地址.png

截图所需要的js

fcccd9221fbd

截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值