之前寫過很多單頁面python爬蟲,感覺python還是很好用的,這里用java總結一個多頁面的爬蟲,迭代爬取種子頁面的所有鏈接的頁面,全部保存在tmp路徑下?! ?/p>
一、 序言
實現這個爬蟲需要兩個數據結構支持,unvisited隊列(priorityqueue:可以適用pagerank等算法計算出url重要度)和visited表(hashset:可以快速查找url是否存在);隊列用于實現寬度優先爬取,visited表用于記錄爬取過的url,不再重復爬取,避免了環。java爬蟲需要的工具包有httpclient和htmlparser1.5,可以在maven repo中查看具體版本的下載。
1、目標網站:新浪 http://www.sina.com.cn/
2、結果截圖:
下面說說爬蟲的實現,后期源碼會上傳到github中,需要的朋友可以留言:
二、爬蟲編程
1、創建種子頁面的url
MyCrawler crawler = new MyCrawler();
crawler.crawling(new String[]{"http://www.sina.com.cn/"});
2、初始化unvisited表為上面的種子url
LinkQueue.addUnvisitedUrl(seeds[i]);
3、最主要的邏輯實現部分:在隊列中取出沒有visit過的url,進行下載,然后加入visited的表,并解析改url頁面上的其它url,把未讀取的加入到unvisited隊列;迭代到隊列為空停止,所以這個url網絡還是很龐大的。注意,這里的頁面下載和頁面解析需要java的工具包實現,下面具體說明下工具包的使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
while (!LinkQueue.unVisitedUrlsEmpty()&&LinkQueue.getVisitedUrlNum()<= 1000 ) { //隊頭URL出隊列 String visitUrl=(String)LinkQueue.unVisitedUrlDeQueue(); if (visitUrl== null ) continue ; DownLoadFile downLoader= new DownLoadFile(); //下載網頁 downLoader.downloadFile(visitUrl); //該 url 放入到已訪問的 URL 中 LinkQueue.addVisitedUrl(visitUrl); //提取出下載網頁中的 URL Set<String> links=HtmlParserTool.extracLinks(visitUrl,filter); //新的未訪問的 URL 入隊 for (String link:links) { LinkQueue.addUnvisitedUrl(link); } } |
4、下面html頁面的download工具包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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.執行 HTTP 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( "Please check your provided http address!" ); e.printStackTrace(); } catch (IOException e) { // 發生網絡異常 e.printStackTrace(); } finally { // 釋放連接 getMethod.releaseConnection(); } return filePath; } |
5、html頁面的解析工具包:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
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() { 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; } |
6、未訪問頁面使用PriorityQueue帶偏好的隊列保存,主要是為了適用于pagerank等算法,有的url忠誠度更高一些;visited表采用hashset實現,注意可以快速查找是否存在;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
public class LinkQueue { //已訪問的 url 集合 private static Set visitedUrl = new HashSet(); //待訪問的 url 集合 private static Queue unVisitedUrl = new PriorityQueue(); //獲得URL隊列 public static Queue getUnVisitedUrl() { return unVisitedUrl; } //添加到訪問過的URL隊列中 public static void addVisitedUrl(String url) { visitedUrl.add(url); } //移除訪問過的URL public static void removeVisitedUrl(String url) { visitedUrl.remove(url); } //未訪問的URL出隊列 public static Object unVisitedUrlDeQueue() { return unVisitedUrl.poll(); } // 保證每個 url 只被訪問一次 public static void addUnvisitedUrl(String url) { if (url != null && !url.trim().equals( "" ) && !visitedUrl.contains(url) && !unVisitedUrl.contains(url)) unVisitedUrl.add(url); } //獲得已經訪問的URL數目 public static int getVisitedUrlNum() { return visitedUrl.size(); } //判斷未訪問的URL隊列中是否為空 public static boolean unVisitedUrlsEmpty() { return unVisitedUrl.isEmpty(); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。