1. 程式人生 > >[轉] [Java] 知乎下巴第5集:使用HttpClient工具包和寬度爬蟲

[轉] [Java] 知乎下巴第5集:使用HttpClient工具包和寬度爬蟲

fan param 出隊 page connect ise dex ide xtra

原文地址: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
  1. import java.io.FileOutputStream;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import org.apache.commons.httpclient.HttpClient;
  5. import org.apache.commons.httpclient.HttpStatus;
  6. import org.apache.commons.httpclient.methods.GetMethod;
  7. /**
  8. *
  9. * @author CallMeWhy
  10. *
  11. */
  12. public class Spider {
  13. private static HttpClient httpClient = new HttpClient();
  14. /**
  15. * @param path
  16. * 目標網頁的鏈接
  17. * @return 返回布爾值,表示是否正常下載目標頁面
  18. * @throws Exception
  19. * 讀取網頁流或寫入本地文件流的IO異常
  20. */
  21. public static boolean downloadPage(String path) throws Exception {
  22. // 定義輸入輸出流
  23. InputStream input = null;
  24. OutputStream output = null;
  25. // 得到 post 方法
  26. GetMethod getMethod = new GetMethod(path);
  27. // 執行,返回狀態碼
  28. int statusCode = httpClient.executeMethod(getMethod);
  29. // 針對狀態碼進行處理
  30. // 簡單起見,只處理返回值為 200 的狀態碼
  31. if (statusCode == HttpStatus.SC_OK) {
  32. input = getMethod.getResponseBodyAsStream();
  33. // 通過對URL的得到文件名
  34. String filename = path.substring(path.lastIndexOf(‘/‘) + 1)
  35. + ".html";
  36. // 獲得文件輸出流
  37. output = new FileOutputStream(filename);
  38. // 輸出到文件
  39. int tempByte = -1;
  40. while ((tempByte = input.read()) > 0) {
  41. output.write(tempByte);
  42. }
  43. // 關閉輸入流
  44. if (input != null) {
  45. input.close();
  46. }
  47. // 關閉輸出流
  48. if (output != null) {
  49. output.close();
  50. }
  51. return true;
  52. }
  53. return false;
  54. }
  55. public static void main(String[] args) {
  56. try {
  57. // 抓取百度首頁,輸出
  58. Spider.downloadPage("http://www.baidu.com");
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. }

但是這樣基本的爬蟲是不能滿足各色各樣的爬蟲需求的。

先來介紹寬度優先爬蟲。

寬度優先相信大家都不陌生,簡單說來可以這樣理解寬度優先爬蟲。

我們把互聯網看作一張超級大的有向圖,每一個網頁上的鏈接都是一個有向邊,每一個文件或沒有鏈接的純頁面則是圖中的終點:

技術分享

寬度優先爬蟲就是這樣一個爬蟲,爬走在這個有向圖上,從根節點開始一層一層往外爬取新的節點的數據。

寬度遍歷算法如下所示:

(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
  1. import java.util.LinkedList;
  2. /**
  3. * 自定義隊列類 保存TODO表
  4. */
  5. public class Queue {
  6. /**
  7. * 定義一個隊列,使用LinkedList實現
  8. */
  9. private LinkedList<Object> queue = new LinkedList<Object>(); // 入隊列
  10. /**
  11. * 將t加入到隊列中
  12. */
  13. public void enQueue(Object t) {
  14. queue.addLast(t);
  15. }
  16. /**
  17. * 移除隊列中的第一項並將其返回
  18. */
  19. public Object deQueue() {
  20. return queue.removeFirst();
  21. }
  22. /**
  23. * 返回隊列是否為空
  24. */
  25. public boolean isQueueEmpty() {
  26. return queue.isEmpty();
  27. }
  28. /**
  29. * 判斷並返回隊列是否包含t
  30. */
  31. public boolean contians(Object t) {
  32. return queue.contains(t);
  33. }
  34. /**
  35. * 判斷並返回隊列是否為空
  36. */
  37. public boolean empty() {
  38. return queue.isEmpty();
  39. }
  40. }


還需要一個數據結構來記錄已經訪問過的 URL,即Visited表。

考慮到這個表的作用,每當要訪問一個 URL 的時候,首先在這個數據結構中進行查找,如果當前的 URL 已經存在,則丟棄這個URL任務。

這個數據結構需要不重復並且能快速查找,所以選擇HashSet來存儲。

綜上,我們另建一個SpiderQueue類來保存Visited表和TODO表:

[java] view plain copy
  1. import java.util.HashSet;
  2. import java.util.Set;
  3. /**
  4. * 自定義類 保存Visited表和unVisited表
  5. */
  6. public class SpiderQueue {
  7. /**
  8. * 已訪問的url集合,即Visited表
  9. */
  10. private static Set<Object> visitedUrl = new HashSet<>();
  11. /**
  12. * 添加到訪問過的 URL 隊列中
  13. */
  14. public static void addVisitedUrl(String url) {
  15. visitedUrl.add(url);
  16. }
  17. /**
  18. * 移除訪問過的 URL
  19. */
  20. public static void removeVisitedUrl(String url) {
  21. visitedUrl.remove(url);
  22. }
  23. /**
  24. * 獲得已經訪問的 URL 數目
  25. */
  26. public static int getVisitedUrlNum() {
  27. return visitedUrl.size();
  28. }
  29. /**
  30. * 待訪問的url集合,即unVisited表
  31. */
  32. private static Queue unVisitedUrl = new Queue();
  33. /**
  34. * 獲得UnVisited隊列
  35. */
  36. public static Queue getUnVisitedUrl() {
  37. return unVisitedUrl;
  38. }
  39. /**
  40. * 未訪問的unVisitedUrl出隊列
  41. */
  42. public static Object unVisitedUrlDeQueue() {
  43. return unVisitedUrl.deQueue();
  44. }
  45. /**
  46. * 保證添加url到unVisitedUrl的時候每個 URL只被訪問一次
  47. */
  48. public static void addUnvisitedUrl(String url) {
  49. if (url != null && !url.trim().equals("") && !visitedUrl.contains(url)
  50. && !unVisitedUrl.contians(url))
  51. unVisitedUrl.enQueue(url);
  52. }
  53. /**
  54. * 判斷未訪問的 URL隊列中是否為空
  55. */
  56. public static boolean unVisitedUrlsEmpty() {
  57. return unVisitedUrl.empty();
  58. }
  59. }


上面是一些自定義類的封裝,接下來就是一個定義一個用來下載網頁的工具類,我們將其定義為DownTool類:

[java] view plain copy
  1. package controller;
  2. import java.io.*;
  3. import org.apache.commons.httpclient.*;
  4. import org.apache.commons.httpclient.methods.*;
  5. import org.apache.commons.httpclient.params.*;
  6. public class DownTool {
  7. /**
  8. * 根據 URL 和網頁類型生成需要保存的網頁的文件名,去除 URL 中的非文件名字符
  9. */
  10. private String getFileNameByUrl(String url, String contentType) {
  11. // 移除 "http://" 這七個字符
  12. url = url.substring(7);
  13. // 確認抓取到的頁面為 text/html 類型
  14. if (contentType.indexOf("html") != -1) {
  15. // 把所有的url中的特殊符號轉化成下劃線
  16. url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
  17. } else {
  18. url = url.replaceAll("[\\?/:*|<>\"]", "_") + "."
  19. + contentType.substring(contentType.lastIndexOf("/") + 1);
  20. }
  21. return url;
  22. }
  23. /**
  24. * 保存網頁字節數組到本地文件,filePath 為要保存的文件的相對地址
  25. */
  26. private void saveToLocal(byte[] data, String filePath) {
  27. try {
  28. DataOutputStream out = new DataOutputStream(new FileOutputStream(
  29. new File(filePath)));
  30. for (int i = 0; i < data.length; i++)
  31. out.write(data[i]);
  32. out.flush();
  33. out.close();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. // 下載 URL 指向的網頁
  39. public String downloadFile(String url) {
  40. String filePath = null;
  41. // 1.生成 HttpClinet對象並設置參數
  42. HttpClient httpClient = new HttpClient();
  43. // 設置 HTTP連接超時 5s
  44. httpClient.getHttpConnectionManager().getParams()
  45. .setConnectionTimeout(5000);
  46. // 2.生成 GetMethod對象並設置參數
  47. GetMethod getMethod = new GetMethod(url);
  48. // 設置 get請求超時 5s
  49. getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
  50. // 設置請求重試處理
  51. getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
  52. new DefaultHttpMethodRetryHandler());
  53. // 3.執行GET請求
  54. try {
  55. int statusCode = httpClient.executeMethod(getMethod);
  56. // 判斷訪問的狀態碼
  57. if (statusCode != HttpStatus.SC_OK) {
  58. System.err.println("Method failed: "
  59. + getMethod.getStatusLine());
  60. filePath = null;
  61. }
  62. // 4.處理 HTTP 響應內容
  63. byte[] responseBody = getMethod.getResponseBody();// 讀取為字節數組
  64. // 根據網頁 url 生成保存時的文件名
  65. filePath = "temp\\"
  66. + getFileNameByUrl(url,
  67. getMethod.getResponseHeader("Content-Type")
  68. .getValue());
  69. saveToLocal(responseBody, filePath);
  70. } catch (HttpException e) {
  71. // 發生致命的異常,可能是協議不對或者返回的內容有問題
  72. System.out.println("請檢查你的http地址是否正確");
  73. e.printStackTrace();
  74. } catch (IOException e) {
  75. // 發生網絡異常
  76. e.printStackTrace();
  77. } finally {
  78. // 釋放連接
  79. getMethod.releaseConnection();
  80. }
  81. return filePath;
  82. }
  83. }

在這裏我們需要一個HtmlParserTool類來處理Html標記:

[java] view plain copy
  1. package controller;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import org.htmlparser.Node;
  5. import org.htmlparser.NodeFilter;
  6. import org.htmlparser.Parser;
  7. import org.htmlparser.filters.NodeClassFilter;
  8. import org.htmlparser.filters.OrFilter;
  9. import org.htmlparser.tags.LinkTag;
  10. import org.htmlparser.util.NodeList;
  11. import org.htmlparser.util.ParserException;
  12. import model.LinkFilter;
  13. public class HtmlParserTool {
  14. // 獲取一個網站上的鏈接,filter 用來過濾鏈接
  15. public static Set<String> extracLinks(String url, LinkFilter filter) {
  16. Set<String> links = new HashSet<String>();
  17. try {
  18. Parser parser = new Parser(url);
  19. parser.setEncoding("gb2312");
  20. // 過濾 <frame >標簽的 filter,用來提取 frame 標簽裏的 src 屬性
  21. NodeFilter frameFilter = new NodeFilter() {
  22. private static final long serialVersionUID = 1L;
  23. @Override
  24. public boolean accept(Node node) {
  25. if (node.getText().startsWith("frame src=")) {
  26. return true;
  27. } else {
  28. return false;
  29. }
  30. }
  31. };
  32. // OrFilter 來設置過濾 <a> 標簽和 <frame> 標簽
  33. OrFilter linkFilter = new OrFilter(new NodeClassFilter(
  34. LinkTag.class), frameFilter);
  35. // 得到所有經過過濾的標簽
  36. NodeList list = parser.extractAllNodesThatMatch(linkFilter);
  37. for (int i = 0; i < list.size(); i++) {
  38. Node tag = list.elementAt(i);
  39. if (tag instanceof LinkTag)// <a> 標簽
  40. {
  41. LinkTag link = (LinkTag) tag;
  42. String linkUrl = link.getLink();// URL
  43. if (filter.accept(linkUrl))
  44. links.add(linkUrl);
  45. } else// <frame> 標簽
  46. {
  47. // 提取 frame 裏 src 屬性的鏈接, 如 <frame src="test.html"/>
  48. String frame = tag.getText();
  49. int start = frame.indexOf("src=");
  50. frame = frame.substring(start);
  51. int end = frame.indexOf(" ");
  52. if (end == -1)
  53. end = frame.indexOf(">");
  54. String frameUrl = frame.substring(5, end - 1);
  55. if (filter.accept(frameUrl))
  56. links.add(frameUrl);
  57. }
  58. }
  59. } catch (ParserException e) {
  60. e.printStackTrace();
  61. }
  62. return links;
  63. }
  64. }

最後我們來寫個爬蟲類調用前面的封裝類和函數:

[java] view plain copy
  1. package controller;
  2. import java.util.Set;
  3. import model.LinkFilter;
  4. import model.SpiderQueue;
  5. public class BfsSpider {
  6. /**
  7. * 使用種子初始化URL隊列
  8. */
  9. private void initCrawlerWithSeeds(String[] seeds) {
  10. for (int i = 0; i < seeds.length; i++)
  11. SpiderQueue.addUnvisitedUrl(seeds[i]);
  12. }
  13. // 定義過濾器,提取以 http://www.xxxx.com開頭的鏈接
  14. public void crawling(String[] seeds) {
  15. LinkFilter filter = new LinkFilter() {
  16. public boolean accept(String url) {
  17. if (url.startsWith("http://www.baidu.com"))
  18. return true;
  19. else
  20. return false;
  21. }
  22. };
  23. // 初始化 URL 隊列
  24. initCrawlerWithSeeds(seeds);
  25. // 循環條件:待抓取的鏈接不空且抓取的網頁不多於 1000
  26. while (!SpiderQueue.unVisitedUrlsEmpty()
  27. && SpiderQueue.getVisitedUrlNum() <= 1000) {
  28. // 隊頭 URL 出隊列
  29. String visitUrl = (String) SpiderQueue.unVisitedUrlDeQueue();
  30. if (visitUrl == null)
  31. continue;
  32. DownTool downLoader = new DownTool();
  33. // 下載網頁
  34. downLoader.downloadFile(visitUrl);
  35. // 該 URL 放入已訪問的 URL 中
  36. SpiderQueue.addVisitedUrl(visitUrl);
  37. // 提取出下載網頁中的 URL
  38. Set<String> links = HtmlParserTool.extracLinks(visitUrl, filter);
  39. // 新的未訪問的 URL 入隊
  40. for (String link : links) {
  41. SpiderQueue.addUnvisitedUrl(link);
  42. }
  43. }
  44. }
  45. // main 方法入口
  46. public static void main(String[] args) {
  47. BfsSpider crawler = new BfsSpider();
  48. crawler.crawling(new String[] { "http://www.baidu.com" });
  49. }
  50. }

運行可以看到,爬蟲已經把百度網頁下所有的頁面都抓取出來了:

技術分享

[轉] [Java] 知乎下巴第5集:使用HttpClient工具包和寬度爬蟲