寬度優先爬蟲的骨架不複雜:從種子節點出發,把種子頁中的超鏈接取出來排入佇列逐個抓取;處理過的鏈接登記到 Visited 表,取新鏈接前先查表,抓過就跳過。下面用 Java 把各個部件逐一實作。
/** 佇列,保存將要訪問的 URL */
public class Queue {
// 使用鏈表實現佇列
private LinkedList queue = new LinkedList();
// 入佇列
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;每次要訪問前先查一次,已存在就丟棄。
public class LinkQueue {
// 已訪問的 url 集合
private static Set visitedUrl = new HashSet();
// 待訪問的 url 集合
private static Queue unVisitedUrl = new Queue();
public static Queue getUnVisitedUrl() {
return unVisitedUrl;
}
public static void addVisitedUrl(String url) {
visitedUrl.add(url);
}
public static void removeVisitedUrl(String url) {
visitedUrl.remove(url);
}
// 未訪問的 URL 出佇列
public static Object unVisitedUrlDeQueue() {
return unVisitedUrl.deQueue();
}
// 保證每個 URL 只被訪問一次
public static void addUnvisitedUrl(String url) {
if (url != null && !url.trim().equals("")
&& !visitedUrl.contains(url)
&& !unVisitedUrl.contians(url)) {
unVisitedUrl.enQueue(url);
}
}
public static int getVisitedUrlNum() {
return visitedUrl.size();
}
public static boolean unVisitedUrlsEmpty() {
return unVisitedUrl.empty();
}
}
public class DownLoadFile {
/** 根據 URL 和網頁類型生成需要保存的檔名,去除 URL 中的非檔名字元 */
public String getFileNameByUrl(String url, String contentType) {
url = url.substring(7); // 移除 http:
if (contentType.indexOf("html") != -1) {
url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
return url;
} else {
return url.replaceAll("[\\?/:*|<>\"]", "_") + "."
+ contentType.substring(contentType.lastIndexOf("/") + 1);
}
}
/** 保存網頁位元組陣列到本地檔案 */
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. 建立 HttpClient 並設定參數
HttpClient httpClient = new HttpClient();
// 連線超時 5 秒
httpClient.getHttpConnectionManager()
.getParam().setConnectionTimeout(5000);
// 2. 建立 GetMethod 並設定參數
GetMethod getMethod = new GetMethod(url);
// 請求超時 5 秒
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. 處理回應內容
byte[] responseBody = getMethod.getResponseBody();
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;
}
}
HtmlParser 是針對 HTML 頁面處理的開源工具包,除了 URL,也能抽文本與其他結構。
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> 標籤,提取其中的 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) {
LinkTag link = (LinkTag) tag;
String linkUrl = link.getLink();
if (filter.accept(linkUrl)) links.add(linkUrl);
} else {
// 提取 frame 裡 src 屬性的鏈接
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;
}
}
public class MyCrawler {
/** 使用種子初始化 URL 佇列 */
private void initCrawlerWithSeeds(String[] seeds) {
for (int i = 0; i < seeds.length; i++) {
LinkQueue.addUnvisitedUrl(seeds[i]);
}
}
/** 抓取過程 */
public void crawling(String[] seeds) {
// 定義過濾器,只提取以 https://www.linuxidc.com 開頭的鏈接
LinkFilter filter = new LinkFilter() {
public boolean accept(String url) {
if (url.startsWith("https://www.linuxidc.com")) {
return true;
} else {
return false;
}
}
};
initCrawlerWithSeeds(seeds);
// 循環條件:待抓取鏈接非空,且抓取數不超過 1000
while (!LinkQueue.unVisitedUrlsEmpty()
&& LinkQueue.getVisitedUrlNum() <= 1000) {
String visitUrl = (String) LinkQueue.unVisitedUrlDeQueue();
if (visitUrl == null) continue;
DownLoadFile downLoader = new DownLoadFile();
downLoader.downloadFile(visitUrl); // 下載網頁
LinkQueue.addVisitedUrl(visitUrl); // 標記為已訪問
Set<String> links = HtmlParserTool.extracLinks(visitUrl, filter);
for (String link : links) {
LinkQueue.addUnvisitedUrl(link); // 新鏈接入佇列
}
}
}
public static void main(String[] args) {
MyCrawler crawler = new MyCrawler();
crawler.crawling(new String[]{"https://www.linuxidc.com"});
}
}
整條鏈路串起來就是:佇列決定順序,Visited 決定去重,下載模組負責落地,解析模組負責發現新節點。四個部件各司其職,替換其中任何一環(例如把 HttpClient 換成別的客戶端、把 gb2312 改成 UTF-8)都不影響主流程。