一、網(wǎng)絡(luò)爬蟲的基本知識(shí)
網(wǎng)絡(luò)爬蟲通過遍歷互聯(lián)網(wǎng)絡(luò),把網(wǎng)絡(luò)中的相關(guān)網(wǎng)頁全部抓取過來,這體現(xiàn)了爬的概念。爬蟲如何遍歷網(wǎng)絡(luò)呢,互聯(lián)網(wǎng)可以看做是一張大圖,每個(gè)頁面看做其中的一個(gè)節(jié)點(diǎn),頁面的連接看做是有向邊。圖的遍歷方式分為寬度遍歷和深度遍歷,但是深度遍歷可能會(huì)在深度上過深的遍歷或者陷入黑洞。所以,大多數(shù)爬蟲不采用這種形式。另一方面,爬蟲在按照寬度優(yōu)先遍歷的方式時(shí)候,會(huì)給待遍歷的網(wǎng)頁賦予一定優(yōu)先級(jí),這種叫做帶偏好的遍歷。
實(shí)際的爬蟲是從一系列的種子鏈接開始。種子鏈接是起始節(jié)點(diǎn),種子頁面的超鏈接指向的頁面是子節(jié)點(diǎn)(中間節(jié)點(diǎn)),對(duì)于非html文檔,如excel等,不能從中提取超鏈接,看做圖的終端節(jié)點(diǎn)。整個(gè)遍歷過程中維護(hù)一張visited表,記錄哪些節(jié)點(diǎn)(鏈接)已經(jīng)處理過了,跳過不作處理。
使用寬度優(yōu)先搜索策略,主要原因有:
a、重要的網(wǎng)頁一般離種子比較近,例如我們打開的新聞網(wǎng)站時(shí)候,往往是最熱門的新聞,隨著深入沖浪,網(wǎng)頁的重要性越來越低。
b、萬維網(wǎng)實(shí)際深度最多達(dá)17層,但到達(dá)某個(gè)網(wǎng)頁總存在一條很短路徑,而寬度優(yōu)先遍歷可以最快的速度找到這個(gè)網(wǎng)頁
c、寬度優(yōu)先有利于多爬蟲合作抓取。
二、網(wǎng)絡(luò)爬蟲的簡單實(shí)現(xiàn)
1、定義已訪問隊(duì)列,待訪問隊(duì)列和爬取得URL的哈希表,包括出隊(duì)列,入隊(duì)列,判斷隊(duì)列是否空等操作
public class LinkQueue {
// 已訪問的 url 集合
private static Set visitedUrl = new HashSet();
// 待訪問的 url 集合
private static Queue unVisitedUrl = new PriorityQueue();
// 獲得URL隊(duì)列
public static Queue getUnVisitedUrl() {
return unVisitedUrl;
}
// 添加到訪問過的URL隊(duì)列中
public static void addVisitedUrl(String url) {
visitedUrl.add(url);
}
// 移除訪問過的URL
public static void removeVisitedUrl(String url) {
visitedUrl.remove(url);
}
// 未訪問的URL出隊(duì)列
public static Object unVisitedUrlDeQueue() {
return unVisitedUrl.poll();
}
// 保證每個(gè) url 只被訪問一次
public static void addUnvisitedUrl(String url) {
if (url != null && !url.trim().equals("") && !visitedUrl.contains(url)
&& !unVisitedUrl.contains(url))
unVisitedUrl.add(url);
}
// 獲得已經(jīng)訪問的URL數(shù)目
public static int getVisitedUrlNum() {
return visitedUrl.size();
}
// 判斷未訪問的URL隊(duì)列中是否為空
public static boolean unVisitedUrlsEmpty() {
return unVisitedUrl.isEmpty();
}
}
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class DownLoadFile {
/**
* 根據(jù) url 和網(wǎng)頁類型生成需要保存的網(wǎng)頁的文件名 去除掉 url 中非文件名字符
*/
public String getFileNameByUrl(String url, String contentType) {
// remove http://
url = url.substring(7);
// text/html類型
if (contentType.indexOf("html") != -1) {
url = url.replaceAll("[//?/:*|<>/"]", "_") + ".html";
return url;
}
// 如application/pdf類型
else {
return url.replaceAll("[//?/:*|<>/"]", "_") + "."
+ contentType.substring(contentType.lastIndexOf("/") + 1);
}
}
/**
* 保存網(wǎng)頁字節(jié)數(shù)組到本地文件 filePath 為要保存的文件的相對(duì)地址
*/
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 對(duì)象并設(shè)置參數(shù) */
HttpClient httpClient = new HttpClient();
// 設(shè)置 Http 連接超時(shí) 5s
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
/* 2.生成 GetMethod 對(duì)象并設(shè)置參數(shù) */
GetMethod getMethod = new GetMethod(url);
// 設(shè)置 get 請(qǐng)求超時(shí) 5s
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 設(shè)置請(qǐng)求重試處理
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
/* 3.執(zhí)行 HTTP GET 請(qǐng)求 */
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 生成保存時(shí)的文件名
filePath = "f://spider//"
+ getFileNameByUrl(url,
getMethod.getResponseHeader("Content-Type")
.getValue());
saveToLocal(responseBody, filePath);
} catch (HttpException e) {
// 發(fā)生致命的異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問題
System.out.println("Please check your provided http address!");
e.printStackTrace();
} catch (IOException e) {
// 發(fā)生網(wǎng)絡(luò)異常
e.printStackTrace();
} finally {
// 釋放連接
getMethod.releaseConnection();
}
return filePath;
}
}
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;
public class HtmlParserTool {
// 獲取一個(gè)網(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("utf-8");
// 過濾 <frame >標(biāo)簽的 filter,用來提取 frame 標(biāo)簽里的 src 屬性所表示的鏈接
NodeFilter frameFilter = new NodeFilter() {
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;
}
}
import java.util.Set;
public class MyCrawler {
/**
* 使用種子初始化 URL 隊(duì)列
*
* @return
* @param seeds
* 種子URL
*/
private void initCrawlerWithSeeds(String[] seeds) {
for (int i = 0; i < seeds.length; i++)
LinkQueue.addUnvisitedUrl(seeds[i]);
}
/**
* 抓取過程
*
* @return
* @param seeds
*/
public void crawling(String[] seeds) { // 定義過濾器,提取以http://www.lietu.com開頭的鏈接
LinkFilter filter = new LinkFilter() {
public boolean accept(String url) {
if (url.startsWith("http://www.baidu.com"))
return true;
else
return false;
}
};
// 初始化 URL 隊(duì)列
initCrawlerWithSeeds(seeds);
// 循環(huán)條件:待抓取的鏈接不空且抓取的網(wǎng)頁不多于1000
while (!LinkQueue.unVisitedUrlsEmpty()
&& LinkQueue.getVisitedUrlNum() <= 1000) {
// 隊(duì)頭URL出隊(duì)列
String visitUrl = (String) LinkQueue.unVisitedUrlDeQueue();
if (visitUrl == null)
continue;
DownLoadFile downLoader = new DownLoadFile();
// 下載網(wǎng)頁
downLoader.downloadFile(visitUrl);
// 該 url 放入到已訪問的 URL 中
LinkQueue.addVisitedUrl(visitUrl);
// 提取出下載網(wǎng)頁中的 URL
Set<String> links = HtmlParserTool.extracLinks(visitUrl, filter);
// 新的未訪問的 URL 入隊(duì)
for (String link : links) {
LinkQueue.addUnvisitedUrl(link);
}
}
}
// main 方法入口
public static void main(String[] args) {
MyCrawler crawler = new MyCrawler();
crawler.crawling(new String[] { "http://www.baidu.com" });
}
}
新聞熱點(diǎn)
疑難解答
圖片精選