一個簡略單純的Java多頁面隊列爬蟲法式。本站提示廣大學習愛好者:(一個簡略單純的Java多頁面隊列爬蟲法式)文章只能為提供參考,不一定能成為您想要的結果。以下是一個簡略單純的Java多頁面隊列爬蟲法式正文
之前寫過許多單頁面python爬蟲,感到python照樣很好用的,這裡用java總結一個多頁面的爬蟲,迭代爬取種子頁面的一切鏈接的頁面,全體保留在tmp途徑下。
1、 序文
完成這個爬蟲須要兩個數據構造支撐,unvisited隊列(priorityqueue:可以實用pagerank等算法盤算出url主要度)和visited表(hashset:可以疾速查找url能否存在);隊列用於完成寬度優先爬取,visited表用於記載爬取過的url,不再反復爬取,防止了環。java爬蟲須要的對象包有httpclient和htmlparser1.5,可以在maven repo中檢查詳細版本的下載。
1、目的網站:新浪 http://www.sina.com.cn/
2、成果截圖:
上面說說爬蟲的完成,前期源碼會上傳到github中,須要的同伙可以留言:
2、爬蟲編程
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的對象包完成,上面詳細解釋下對象包的應用。
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對象包
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頁面的解析對象包:
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完成,留意可以疾速查找能否存在;
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();
}
}
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。