零基礎寫Java知乎爬蟲之進階篇
說到爬蟲,使用Java本身自帶的URLConnection可以實現一些基本的抓取頁面的功能,但是對於一些比較高階的功能,比如重定向的處理,HTML標記的去除,僅僅使用URLConnection還是不夠的。
在這裡我們可以使用HttpClient這個第三方jar包。
接下來我們使用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
* 目標網頁的連結
* @return 返回布林值,表示是否正常下載目標頁面
* @throws Exception
* 讀取網頁流或寫入本地檔案流的IO異常
*/
public static boolean downloadPage(String path) throws Exception {
// 定義輸入輸出流
InputStream input = null;
OutputStream output = null;
// 得到 post 方法
GetMethod getMethod = new GetMethod(path);
// 執行,返回狀態碼
int statusCode = httpClient.executeMethod(getMethod);
// 針對狀態碼進行處理
// 簡單起見,只處理返回值為 200 的狀態碼
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);
}
// 關閉輸入流
if (input != null) {
input.close();
}
// 關閉輸出流
if (output != null) {
output.close();
}
return true;
}
return false;
}
public static void main(String[] args) {
try {
// 抓取百度首頁,輸出
Spider.downloadPage(" http://www.baidu.com");
} catch (Exception e) {
e.printStackTrace();
}
}
}
但是這樣基本的爬蟲是不能滿足各色各樣的爬蟲需求的。
先來介紹寬度優先爬蟲。
寬度優先相信大家都不陌生,簡單說來可以這樣理解寬度優先爬蟲。
我們把網際網路看作一張超級大的有向圖,每一個網頁上的連結都是一個有向邊,每一個檔案或沒有連結的純頁面則是圖中的終點:
寬度優先爬蟲就是這樣一個爬蟲,爬走在這個有向圖上,從根節點開始一層一層往外爬取新的節點的資料。
寬度遍歷演算法如下所示:
(1) 頂點 V 入佇列。
(2) 當佇列非空時繼續執行,否則演算法為空。
(3) 出佇列,獲得隊頭節點 V,訪問頂點 V 並標記 V 已經被訪問。
(4) 查詢頂點 V 的第一個鄰接頂點 col。
(5) 若 V 的鄰接頂點 col 未被訪問過,則 col 進佇列。
(6) 繼續查詢 V 的其他鄰接頂點 col,轉到步驟(5),若 V 的所有鄰接頂點都已經被訪問過,則轉到步驟(2)。
按照寬度遍歷演算法,上圖的遍歷順序為:A->B->C->D->E->F->H->G->I,這樣一層一層的遍歷下去。
而寬度優先爬蟲其實爬取的是一系列的種子節點,和圖的遍歷基本相同。
我們可以把需要爬取頁面的URL都放在一個TODO表中,將已經訪問的頁面放在一個Visited表中:
則寬度優先爬蟲的基本流程如下:
(1) 把解析出的連結和 Visited 表中的連結進行比較,若 Visited 表中不存在此連結, 表示其未被訪問過。
(2) 把連結放入 TODO 表中。
(3) 處理完畢後,從 TODO 表中取得一條連結,直接放入 Visited 表中。
(4) 針對這個連結所表示的網頁,繼續上述過程。如此迴圈往復。
下面我們就來一步一步製作一個寬度優先的爬蟲。
首先,對於先設計一個數據結構用來儲存TODO表, 考慮到需要先進先出所以採用佇列,自定義一個Quere類:
import java.util.LinkedList;
/**
* 自定義佇列類 儲存TODO表
*/
public class Queue {
/**
* 定義一個佇列,使用LinkedList實現
*/
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();
}
}
還需要一個數據結構來記錄已經訪問過的 URL,即Visited表。
考慮到這個表的作用,每當要訪問一個 URL 的時候,首先在這個資料結構中進行查詢,如果當前的 URL 已經存在,則丟棄這個URL任務。
這個資料結構需要不重複並且能快速查詢,所以選擇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);
}
/**
* 獲得已經訪問的 URL 數目
*/
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();
}
}
上面是一些自定義類的封裝,接下來就是一個定義一個用來下載網頁的工具類,我們將其定義為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 {
/**
* 根據 URL 和網頁型別生成需要儲存的網頁的檔名,去除 URL 中的非檔名字元
*/
private String getFileNameByUrl(String url, String contentType) {
// 移除 "http://" 這七個字元
url = url.substring(7);
// 確認抓取到的頁面為 text/html 型別
if (contentType.indexOf("html") != -1) {
// 把所有的url中的特殊符號轉化成下劃線
url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
} else {
url = url.replaceAll("[\\?/:*|<>\"]", "_") + "."
+ contentType.substring(contentType.lastIndexOf("/") + 1);
}
return url;
}
/**
* 儲存網頁位元組陣列到本地檔案,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 指向的網頁
public String downloadFile(String url) {
String filePath = null;
// 1.生成 HttpClinet物件並設定引數
HttpClient httpClient = new HttpClient();
// 設定 HTTP連線超時 5s
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
// 2.生成 GetMethod物件並設定引數
GetMethod getMethod = new GetMethod(url);
// 設定 get請求超時 5s
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 設定請求重試處理
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
// 3.執行GET請求
try {
int statusCode = httpClient.executeMethod(getMethod);
// 判斷訪問的狀態碼
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
filePath = null;
}
// 4.處理 HTTP 響應內容
byte[] responseBody = getMethod.getResponseBody();// 讀取為位元組陣列
// 根據網頁 url 生成儲存時的檔名
filePath = "temp\\"
+ getFileNameByUrl(url,
getMethod.getResponseHeader("Content-Type")
.getValue());
saveToLocal(responseBody, filePath);
} catch (HttpException e) {
// 發生致命的異常,可能是協議不對或者返回的內容有問題
System.out.println("請檢查你的http地址是否正確");
e.printStackTrace();
} catch (IOException e) {
// 發生網路異常
e.printStackTrace();
} finally {
// 釋放連線
getMethod.releaseConnection();
}
return filePath;
}
}
在這裡我們需要一個HtmlParserTool類來處理Html標記:
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 {
// 獲取一個網站上的連結,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 >標籤的 filter,用來提取 frame 標籤裡的 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 來設定過濾 <a> 標籤和 <frame> 標籤
OrFilter linkFilter = new OrFilter(new NodeClassFilter(
LinkTag.class), frameFilter);
// 得到所有經過過濾的標籤
NodeList list = parser.extractAllNodesThatMatch(linkFilter);
for (int i = 0; i < list.size(); i++) {
Node tag = list.elementAt(i);
if (tag instanceof LinkTag)// <a> 標籤
{
LinkTag link = (LinkTag) tag;
String linkUrl = link.getLink();// URL
if (filter.accept(linkUrl))
links.add(linkUrl);
} else// <frame> 標籤
{
// 提取 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;
}
}
最後我們來寫個爬蟲類呼叫前面的封裝類和函式:
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("http://www.baidu.com"))
return true;
else
return false;
}
};
// 初始化 URL 佇列
initCrawlerWithSeeds(seeds);
// 迴圈條件:待抓取的連結不空且抓取的網頁不多於 1000
while (!SpiderQueue.unVisitedUrlsEmpty()
&& SpiderQueue.getVisitedUrlNum() <= 1000) {
// 隊頭 URL 出佇列
String visitUrl = (String) SpiderQueue.unVisitedUrlDeQueue();
if (visitUrl == null)
continue;
DownTool downLoader = new DownTool();
// 下載網頁
downLoader.downloadFile(visitUrl);
// 該 URL 放入已訪問的 URL 中
SpiderQueue.addVisitedUrl(visitUrl);
// 提取出下載網頁中的 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[] { "http://www.baidu.com" });
}
}
執行可以看到,爬蟲已經把百度網頁下所有的頁面都抓取出來了:
以上就是java使用HttpClient工具包和寬度爬蟲進行抓取內容的操作的全部內容,稍微複雜點,小夥伴們要仔細琢磨下哦,希望對大家能有所幫助