java在進行爬蟲過程中會因為網(wǎng)站作出反爬措施,導致抓取的內(nèi)容不全面忌警,所以需要利用模擬瀏覽器,打開頁面獲取到頁面的全部內(nèi)容。本文以騰訊新聞https://news.qq.com/為例筐喳。
環(huán)境配置參考http://www.reibang.com/p/6c3d90bef17f,可以配置nodejs的環(huán)境函喉。
一避归、使用jsoup解析網(wǎng)頁,當解析騰訊新聞時只能獲取到網(wǎng)頁的源碼管呵,其他與新聞相關的內(nèi)容一概獲取不到梳毙,從而無法抓取到有用的信息。
/**
* 利用jsoup解析網(wǎng)頁
* @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;
}
測試獲取的結果捐下,獲取不到新聞列表
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 {
//執(zhí)行腳本命令
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;
}
運行獲取到的結果
result2.png
而在任務執(zhí)行過程中所需要的渲染頁面的js
render.png
寫好js后可以利用cdm進行測試坷襟。java中也可以利用相同的方法進行截圖奸柬。只需要在程序中將js換掉就行。并增加一個參數(shù)
截圖地址.png
截圖所需要的js
截圖