零基礎(chǔ)寫Java知乎爬蟲之進階篇
說到爬蟲,使用Java本身自帶的URLConnection可以實現(xiàn)一些基本的抓取頁面的功能,但是對于一些比較高級的功能,比如重定向的處理,HTML標(biāo)記的去除,僅僅使用URLConnection還是不夠的。
在這里我們可以使用HttpClient這個第三方j(luò)ar包。
接下來我們使用HttpClient簡單的寫一個爬去百度的Demo:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
/**
*
* @author CallMeWhy
*
*/
public class Spider {
private static HttpClient httpClient = new HttpClient();
/**
* @param path
* 目標(biāo)網(wǎng)頁的鏈接
* @return 返回布爾值,表示是否正常下載目標(biāo)頁面
* @throws Exception
* 讀取網(wǎng)頁流或?qū)懭氡镜匚募鞯腎O異常
*/
public static boolean downloadPage(String path) throws Exception {
// 定義輸入輸出流
InputStream input = null;
OutputStream output = null;
// 得到 post 方法
GetMethod getMethod = new GetMethod(path);
// 執(zhí)行,返回狀態(tài)碼
int statusCode = httpClient.executeMethod(getMethod);
// 針對狀態(tài)碼進行處理
// 簡單起見,只處理返回值為 200 的狀態(tài)碼
if (statusCode == HttpStatus.SC_OK) {
input = getMethod.getResponseBodyAsStream();
// 通過對URL的得到文件名
String filename = path.substring(path.lastIndexOf('/') + 1)
+ ".html";
// 獲得文件輸出流
output = new FileOutputStream(filename);
// 輸出到文件
int tempByte = -1;
while ((tempByte = input.read()) > 0) {
output.write(tempByte);
}
// 關(guān)閉輸入流
if (input != null) {
input.close();
}
// 關(guān)閉輸出流
if (output != null) {
output.close();
}
return true;
}
return false;
}
public static void main(String[] args) {
try {
// 抓取百度首頁,輸出
Spider.downloadPage(" } catch (Exception e) {
e.printStackTrace();
}
}
}
但是這樣基本的爬蟲是不能滿足各色各樣的爬蟲需求的。
先來介紹寬度優(yōu)先爬蟲。
寬度優(yōu)先相信大家都不陌生,簡單說來可以這樣理解寬度優(yōu)先爬蟲。
我們把互聯(lián)網(wǎng)看作一張超級大的有向圖,每一個網(wǎng)頁上的鏈接都是一個有向邊,每一個文件或沒有鏈接的純頁面則是圖中的終點:
寬度優(yōu)先爬蟲就是這樣一個爬蟲,爬走在這個有向圖上,從根節(jié)點開始一層一層往外爬取新的節(jié)點的數(shù)據(jù)。
寬度遍歷算法如下所示:
(1) 頂點 V 入隊列。
(2) 當(dāng)隊列非空時繼續(xù)執(zhí)行,否則算法為空。
(3) 出隊列,獲得隊頭節(jié)點 V,訪問頂點 V 并標(biāo)記 V 已經(jīng)被訪問。
(4) 查找頂點 V 的第一個鄰接頂點 col。
(5) 若 V 的鄰接頂點 col 未被訪問過,則 col 進隊列。
(6) 繼續(xù)查找 V 的其他鄰接頂點 col,轉(zhuǎn)到步驟(5),若 V 的所有鄰接頂點都已經(jīng)被訪問過,則轉(zhuǎn)到步驟(2)。
按照寬度遍歷算法,上圖的遍歷順序為:A->B->C->D->E->F->H->G->I,這樣一層一層的遍歷下去。
而寬度優(yōu)先爬蟲其實爬取的是一系列的種子節(jié)點,和圖的遍歷基本相同。
我們可以把需要爬取頁面的URL都放在一個TODO表中,將已經(jīng)訪問的頁面放在一個Visited表中:
則寬度優(yōu)先爬蟲的基本流程如下:
(1) 把解析出的鏈接和 Visited 表中的鏈接進行比較,若 Visited 表中不存在此鏈接, 表示其未被訪問過。
(2) 把鏈接放入 TODO 表中。
(3) 處理完畢后,從 TODO 表中取得一條鏈接,直接放入 Visited 表中。
(4) 針對這個鏈接所表示的網(wǎng)頁,繼續(xù)上述過程。如此循環(huán)往復(fù)。
下面我們就來一步一步制作一個寬度優(yōu)先的爬蟲。
首先,對于先設(shè)計一個數(shù)據(jù)結(jié)構(gòu)用來存儲TODO表, 考慮到需要先進先出所以采用隊列,自定義一個Quere類:
import java.util.LinkedList;
/**
* 自定義隊列類 保存TODO表
*/
public class Queue {
/**
* 定義一個隊列,使用LinkedList實現(xiàn)
*/
private LinkedList<Object> queue = new LinkedList<Object>(); // 入隊列
/**
* 將t加入到隊列中
*/
public void enQueue(Object t) {
queue.addLast(t);
}
/**
* 移除隊列中的第一項并將其返回
*/
public Object deQueue() {
return queue.removeFirst();
}
/**
* 返回隊列是否為空
*/
public boolean isQueueEmpty() {
return queue.isEmpty();
}
/**
* 判斷并返回隊列是否包含t
*/
public boolean contians(Object t) {
return queue.contains(t);
}
/**
* 判斷并返回隊列是否為空
*/
public boolean empty() {
return queue.isEmpty();
}
}
還需要一個數(shù)據(jù)結(jié)構(gòu)來記錄已經(jīng)訪問過的 URL,即Visited表。
考慮到這個表的作用,每當(dāng)要訪問一個 URL 的時候,首先在這個數(shù)據(jù)結(jié)構(gòu)中進行查找,如果當(dāng)前的 URL 已經(jīng)存在,則丟棄這個URL任務(wù)。
這個數(shù)據(jù)結(jié)構(gòu)需要不重復(fù)并且能快速查找,所以選擇HashSet來存儲。
綜上,我們另建一個SpiderQueue類來保存Visited表和TODO表:
import java.util.HashSet;
import java.util.Set;
/**
* 自定義類 保存Visited表和unVisited表
*/
public class SpiderQueue {
/**
* 已訪問的url集合,即Visited表
*/
private static Set<Object> visitedUrl = new HashSet<>();
/**
* 添加到訪問過的 URL 隊列中
*/
public static void addVisitedUrl(String url) {
visitedUrl.add(url);
}
/**
* 移除訪問過的 URL
*/
public static void removeVisitedUrl(String url) {
visitedUrl.remove(url);
}
/**
* 獲得已經(jīng)訪問的 URL 數(shù)目
*/
public static int getVisitedUrlNum() {
return visitedUrl.size();
}
/**
* 待訪問的url集合,即unVisited表
*/
private static Queue unVisitedUrl = new Queue();
/**
* 獲得UnVisited隊列
*/
public static Queue getUnVisitedUrl() {
return unVisitedUrl;
}
/**
* 未訪問的unVisitedUrl出隊列
*/
public static Object unVisitedUrlDeQueue() {
return unVisitedUrl.deQueue();
}
/**
* 保證添加url到unVisitedUrl的時候每個 URL只被訪問一次
*/
public static void addUnvisitedUrl(String url) {
if (url != null && !url.trim().equals("") && !visitedUrl.contains(url)
&& !unVisitedUrl.contians(url))
unVisitedUrl.enQueue(url);
}
/**
* 判斷未訪問的 URL隊列中是否為空
*/
public static boolean unVisitedUrlsEmpty() {
return unVisitedUrl.empty();
}
}
上面是一些自定義類的封裝,接下來就是一個定義一個用來下載網(wǎng)頁的工具類,我們將其定義為DownTool類:
package controller;
import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.*;
public class DownTool {
/**
* 根據(jù) URL 和網(wǎng)頁類型生成需要保存的網(wǎng)頁的文件名,去除 URL 中的非文件名字符
*/
private String getFileNameByUrl(String url, String contentType) {
// 移除 "http://" 這七個字符
url = url.substring(7);
// 確認(rèn)抓取到的頁面為 text/html 類型
if (contentType.indexOf("html") != -1) {
// 把所有的url中的特殊符號轉(zhuǎn)化成下劃線
url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
} else {
url = url.replaceAll("[\\?/:*|<>\"]", "_") + "."
+ contentType.substring(contentType.lastIndexOf("/") + 1);
}
return url;
}
/**
* 保存網(wǎng)頁字節(jié)數(shù)組到本地文件,filePath 為要保存的文件的相對地址
*/
private void saveToLocal(byte[] data, String filePath) {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(
new File(filePath)));
for (int i = 0; i < data.length; i++)
out.write(data[i]);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 下載 URL 指向的網(wǎng)頁
public String downloadFile(String url) {
String filePath = null;
// 1.生成 HttpClinet對象并設(shè)置參數(shù)
HttpClient httpClient = new HttpClient();
// 設(shè)置 HTTP連接超時 5s
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
// 2.生成 GetMethod對象并設(shè)置參數(shù)
GetMethod getMethod = new GetMethod(url);
// 設(shè)置 get請求超時 5s
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 設(shè)置請求重試處理
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
// 3.執(zhí)行GET請求
try {
int statusCode = httpClient.executeMethod(getMethod);
// 判斷訪問的狀態(tài)碼
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
filePath = null;
}
// 4.處理 HTTP 響應(yīng)內(nèi)容
byte[] responseBody = getMethod.getResponseBody();// 讀取為字節(jié)數(shù)組
// 根據(jù)網(wǎng)頁 url 生成保存時的文件名
filePath = "temp\\"
+ getFileNameByUrl(url,
getMethod.getResponseHeader("Content-Type")
.getValue());
saveToLocal(responseBody, filePath);
} catch (HttpException e) {
// 發(fā)生致命的異常,可能是協(xié)議不對或者返回的內(nèi)容有問題
System.out.println("請檢查你的http地址是否正確");
e.printStackTrace();
} catch (IOException e) {
// 發(fā)生網(wǎng)絡(luò)異常
e.printStackTrace();
} finally {
// 釋放連接
getMethod.releaseConnection();
}
return filePath;
}
}
在這里我們需要一個HtmlParserTool類來處理Html標(biāo)記:
package controller;
import java.util.HashSet;
import java.util.Set;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import model.LinkFilter;
public class HtmlParserTool {
// 獲取一個網(wǎng)站上的鏈接,filter 用來過濾鏈接
public static Set<String> extracLinks(String url, LinkFilter filter) {
Set<String> links = new HashSet<String>();
try {
Parser parser = new Parser(url);
parser.setEncoding("gb2312");
// 過濾 <frame >標(biāo)簽的 filter,用來提取 frame 標(biāo)簽里的 src 屬性
NodeFilter frameFilter = new NodeFilter() {
private static final long serialVersionUID = 1L;
@Override
public boolean accept(Node node) {
if (node.getText().startsWith("frame src=")) {
return true;
} else {
return false;
}
}
};
// OrFilter 來設(shè)置過濾 <a> 標(biāo)簽和 <frame> 標(biāo)簽
OrFilter linkFilter = new OrFilter(new NodeClassFilter(
LinkTag.class), frameFilter);
// 得到所有經(jīng)過過濾的標(biāo)簽
NodeList list = parser.extractAllNodesThatMatch(linkFilter);
for (int i = 0; i < list.size(); i++) {
Node tag = list.elementAt(i);
if (tag instanceof LinkTag)// <a> 標(biāo)簽
{
LinkTag link = (LinkTag) tag;
String linkUrl = link.getLink();// URL
if (filter.accept(linkUrl))
links.add(linkUrl);
} else// <frame> 標(biāo)簽
{
// 提取 frame 里 src 屬性的鏈接, 如 <frame src="test.html"/>
String frame = tag.getText();
int start = frame.indexOf("src=");
frame = frame.substring(start);
int end = frame.indexOf(" ");
if (end == -1)
end = frame.indexOf(">");
String frameUrl = frame.substring(5, end - 1);
if (filter.accept(frameUrl))
links.add(frameUrl);
}
}
} catch (ParserException e) {
e.printStackTrace();
}
return links;
}
}
最后我們來寫個爬蟲類調(diào)用前面的封裝類和函數(shù):
package controller;
import java.util.Set;
import model.LinkFilter;
import model.SpiderQueue;
public class BfsSpider {
/**
* 使用種子初始化URL隊列
*/
private void initCrawlerWithSeeds(String[] seeds) {
for (int i = 0; i < seeds.length; i++)
SpiderQueue.addUnvisitedUrl(seeds[i]);
}
// 定義過濾器,提取以 http://www.xxxx.com開頭的鏈接
public void crawling(String[] seeds) {
LinkFilter filter = new LinkFilter() {
public boolean accept(String url) {
if (url.startsWith(" return true;
else
return false;
}
};
// 初始化 URL 隊列
initCrawlerWithSeeds(seeds);
// 循環(huán)條件:待抓取的鏈接不空且抓取的網(wǎng)頁不多于 1000
while (!SpiderQueue.unVisitedUrlsEmpty()
&& SpiderQueue.getVisitedUrlNum() <= 1000) {
// 隊頭 URL 出隊列
String visitUrl = (String) SpiderQueue.unVisitedUrlDeQueue();
if (visitUrl == null)
continue;
DownTool downLoader = new DownTool();
// 下載網(wǎng)頁
downLoader.downloadFile(visitUrl);
// 該 URL 放入已訪問的 URL 中
SpiderQueue.addVisitedUrl(visitUrl);
// 提取出下載網(wǎng)頁中的 URL
Set<String> links = HtmlParserTool.extracLinks(visitUrl, filter);
// 新的未訪問的 URL 入隊
for (String link : links) {
SpiderQueue.addUnvisitedUrl(link);
}
}
}
// main 方法入口
public static void main(String[] args) {
BfsSpider crawler = new BfsSpider();
crawler.crawling(new String[] { " }
}
運行可以看到,爬蟲已經(jīng)把百度網(wǎng)頁下所有的頁面都抓取出來了:
以上就是java使用HttpClient工具包和寬度爬蟲進行抓取內(nèi)容的操作的全部內(nèi)容,稍微復(fù)雜點,小伙伴們要仔細(xì)琢磨下哦,希望對大家能有所幫助
相關(guān)文章
spring cloud gateway如何獲取請求的真實地址
這篇文章主要介紹了spring cloud gateway如何獲取請求的真實地址問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05Sharding-JDBC自動實現(xiàn)MySQL讀寫分離的示例代碼
本文主要介紹了Sharding-JDBC自動實現(xiàn)MySQL讀寫分離,優(yōu)點在于數(shù)據(jù)源完全有Sharding-JDBC托管,寫操作自動執(zhí)行master庫,讀操作自動執(zhí)行slave庫,感興趣的可以了解一下2021-11-11java實現(xiàn)excel自定義樣式與字段導(dǎo)出詳細(xì)圖文教程
最近接到一個需求,客戶不滿意原本導(dǎo)出的csv文件,想要導(dǎo)出Excel文件,下面這篇文章主要給大家介紹了關(guān)于java實現(xiàn)excel自定義樣式與字段導(dǎo)出詳細(xì)圖文教程2023-09-09