[轉] [Java] 知乎下巴第5集:使用HttpClient工具包和寬度爬蟲
原文地址:http://blog.csdn.net/pleasecallmewhy/article/details/18010015
下載地址:https://code.csdn.net/wxg694175346/zhihudown
說到爬蟲,使用Java本身自帶的URLConnection可以實現一些基本的抓取頁面的功能,但是對於一些比較高級的功能,比如重定向的處理,HTML標記的去除,僅僅使用URLConnection還是不夠的。
在這裏我們可以使用HttpClient這個第三方jar包,下載地址點擊這裏。
接下來我們使用HttpClient簡單的寫一個爬去百度的Demo:
[cpp] view plain copy
- 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類:
[java] view plain copy- 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表:
[java] view plain copy
- 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類:
[java] view plain copy
- 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標記:
[java] view plain copy
- 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;
- }
- }
最後我們來寫個爬蟲類調用前面的封裝類和函數:
[java] view plain copy
- 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] 知乎下巴第5集:使用HttpClient工具包和寬度爬蟲