一個簡易的Java多頁面隊(duì)列爬蟲程序
之前寫過很多單頁面python爬蟲,感覺python還是很好用的,這里用java總結(jié)一個多頁面的爬蟲,迭代爬取種子頁面的所有鏈接的頁面,全部保存在tmp路徑下。
一、 序言
實(shí)現(xiàn)這個爬蟲需要兩個數(shù)據(jù)結(jié)構(gòu)支持,unvisited隊(duì)列(priorityqueue:可以適用pagerank等算法計(jì)算出url重要度)和visited表(hashset:可以快速查找url是否存在);隊(duì)列用于實(shí)現(xiàn)寬度優(yōu)先爬取,visited表用于記錄爬取過的url,不再重復(fù)爬取,避免了環(huán)。java爬蟲需要的工具包有httpclient和htmlparser1.5,可以在maven repo中查看具體版本的下載。
1、目標(biāo)網(wǎng)站:新浪 http://www.sina.com.cn/
2、結(jié)果截圖:

下面說說爬蟲的實(shí)現(xiàn),后期源碼會上傳到github中,需要的朋友可以留言:
二、爬蟲編程
1、創(chuàng)建種子頁面的url
MyCrawler crawler = new MyCrawler();
crawler.crawling(new String[]{"http://www.sina.com.cn/"});
2、初始化unvisited表為上面的種子url
LinkQueue.addUnvisitedUrl(seeds[i]);
3、最主要的邏輯實(shí)現(xiàn)部分:在隊(duì)列中取出沒有visit過的url,進(jìn)行下載,然后加入visited的表,并解析改url頁面上的其它url,把未讀取的加入到unvisited隊(duì)列;迭代到隊(duì)列為空停止,所以這個url網(wǎng)絡(luò)還是很龐大的。注意,這里的頁面下載和頁面解析需要java的工具包實(shí)現(xiàn),下面具體說明下工具包的使用。
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);
}
}
4、下面html頁面的download工具包
public String downloadFile(String url) {
String filePath = null;
/* 1.生成 HttpClinet 對象并設(shè)置參數(shù) */
HttpClient httpClient = new HttpClient();
// 設(shè)置 Http 連接超時 5s
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(
5000);
/* 2.生成 GetMethod 對象并設(shè)置參數(shù) */
GetMethod getMethod = new GetMethod(url);
// 設(shè)置 get 請求超時 5s
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 設(shè)置請求重試處理
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
/* 3.執(zhí)行 HTTP GET 請求 */
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 生成保存時的文件名
filePath = "temp\\"
+ getFileNameByUrl(url, getMethod.getResponseHeader(
"Content-Type").getValue());
saveToLocal(responseBody, filePath);
} catch (HttpException e) {
// 發(fā)生致命的異常,可能是協(xié)議不對或者返回的內(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;
}
5、html頁面的解析工具包:
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 >標(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;
}
6、未訪問頁面使用PriorityQueue帶偏好的隊(duì)列保存,主要是為了適用于pagerank等算法,有的url忠誠度更高一些;visited表采用hashset實(shí)現(xiàn),注意可以快速查找是否存在;
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();
}
// 保證每個 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();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java利用delayedQueue實(shí)現(xiàn)本地的延遲隊(duì)列
- Java 隊(duì)列實(shí)現(xiàn)原理及簡單實(shí)現(xiàn)代碼
- 剖析Java中阻塞隊(duì)列的實(shí)現(xiàn)原理及應(yīng)用場景
- 詳解Java消息隊(duì)列-Spring整合ActiveMq
- 解析Java中的隊(duì)列和用LinkedList集合模擬隊(duì)列的方法
- java結(jié)合WebSphere MQ實(shí)現(xiàn)接收隊(duì)列文件功能
- java使用數(shù)組和鏈表實(shí)現(xiàn)隊(duì)列示例
- Java 阻塞隊(duì)列詳解及簡單使用
- Java消息隊(duì)列的簡單實(shí)現(xiàn)代碼
- Java并發(fā)編程之阻塞隊(duì)列詳解
- java多線程消息隊(duì)列的實(shí)現(xiàn)代碼
- Java延遲隊(duì)列原理與用法實(shí)例詳解
相關(guān)文章
java使用BeanUtils.copyProperties方法對象復(fù)制同名字段類型不同賦值為空問題解決方案
這篇文章主要給大家介紹了關(guān)于java使用BeanUtils.copyProperties方法對象復(fù)制同名字段類型不同賦值為空問題的解決方案,文中通過代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-11-11
關(guān)于SpringBoot獲取IOC容器中注入的Bean(推薦)
本文通過實(shí)例代碼給大家詳解了springboot獲取ioc容器中注入的bean問題,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-05-05
如何巧用HashMap一行代碼統(tǒng)計(jì)單詞出現(xiàn)次數(shù)詳解
這篇文章主要給大家介紹了關(guān)于如何巧用HashMap一行代碼統(tǒng)計(jì)單詞出現(xiàn)次數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
解決Mybatis 大數(shù)據(jù)量的批量insert問題
這篇文章主要介紹了解決Mybatis 大數(shù)據(jù)量的批量insert問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
Spring中的DeferredImportSelector實(shí)現(xiàn)詳解
這篇文章主要介紹了Spring中的DeferredImportSelector實(shí)現(xiàn)詳解,兩個官方的實(shí)現(xiàn)類AutoConfigurationImportSelector和ImportAutoConfigurationImportSelector都是Spring Boot后新增的實(shí)現(xiàn),需要的朋友可以參考下2024-01-01

