半小時(shí)實(shí)現(xiàn)Java手?jǐn)]網(wǎng)絡(luò)爬蟲(chóng)框架(附完整源碼)
最近在做一個(gè)搜索相關(guān)的項(xiàng)目,需要爬取網(wǎng)絡(luò)上的一些鏈接存儲(chǔ)到索引庫(kù)中,雖然有很多開(kāi)源的強(qiáng)大的爬蟲(chóng)框架,但本著學(xué)習(xí)的態(tài)度,自己寫(xiě)了一個(gè)簡(jiǎn)單的網(wǎng)絡(luò)爬蟲(chóng),以便了解其中的原理。今天,就為小伙伴們分享下這個(gè)簡(jiǎn)單的爬蟲(chóng)程序!!
首先介紹每個(gè)類(lèi)的功能:
- DownloadPage.java的功能是下載此超鏈接的頁(yè)面源代碼.
- FunctionUtils.java 的功能是提供不同的靜態(tài)方法,包括:頁(yè)面鏈接正則表達(dá)式匹配,獲取URL鏈接的元素,判斷是否創(chuàng)建文件,獲取頁(yè)面的Url并將其轉(zhuǎn)換為規(guī)范的Url,截取網(wǎng)頁(yè)網(wǎng)頁(yè)源文件的目標(biāo)內(nèi)容。
- HrefOfPage.java 的功能是獲取頁(yè)面源代碼的超鏈接。
- UrlDataHanding.java 的功能是整合各個(gè)給類(lèi),實(shí)現(xiàn)url到獲取數(shù)據(jù)到數(shù)據(jù)處理類(lèi)。
- UrlQueue.java 的未訪問(wèn)Url隊(duì)列。
- VisitedUrlQueue.java 已訪問(wèn)過(guò)的URL隊(duì)列。
下面介紹一下每個(gè)類(lèi)的源代碼:
DownloadPage.java 此類(lèi)要用到HttpClient組件。
package com.sreach.spider;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* @author binghe
*/
public class DownloadPage {
/**
* 根據(jù)URL抓取網(wǎng)頁(yè)內(nèi)容
*
* @param url
* @return
*/
public static String getContentFormUrl(String url) {
/* 實(shí)例化一個(gè)HttpClient客戶端 */
HttpClient client = new DefaultHttpClient();
HttpGet getHttp = new HttpGet(url);
String content = null;
HttpResponse response;
try {
/* 獲得信息載體 */
response = client.execute(getHttp);
HttpEntity entity = response.getEntity();
VisitedUrlQueue.addElem(url);
if (entity != null) {
/* 轉(zhuǎn)化為文本信息 */
content = EntityUtils.toString(entity);
/* 判斷是否符合下載網(wǎng)頁(yè)源代碼到本地的條件 */
if (FunctionUtils.isCreateFile(url)
&& FunctionUtils.isHasGoalContent(content) != -1) {
FunctionUtils.createFile(
FunctionUtils.getGoalContent(content), url);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return content;
}
}
FunctionUtils.java 此類(lèi)的方法均為static方法
package com.sreach.spider;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author binghe
*/
public class FunctionUtils {
/**
* 匹配超鏈接的正則表達(dá)式
*/
private static String pat = "http://www\\.oschina\\.net/code/explore/.*/\\w+\\.[a-zA-Z]+";
private static Pattern pattern = Pattern.compile(pat);
private static BufferedWriter writer = null;
/**
* 爬蟲(chóng)搜索深度
*/
public static int depth = 0;
/**
* 以"/"來(lái)分割URL,獲得超鏈接的元素
*
* @param url
* @return
*/
public static String[] divUrl(String url) {
return url.split("/");
}
/**
* 判斷是否創(chuàng)建文件
*
* @param url
* @return
*/
public static boolean isCreateFile(String url) {
Matcher matcher = pattern.matcher(url);
return matcher.matches();
}
/**
* 創(chuàng)建對(duì)應(yīng)文件
*
* @param content
* @param urlPath
*/
public static void createFile(String content, String urlPath) {
/* 分割url */
String[] elems = divUrl(urlPath);
StringBuffer path = new StringBuffer();
File file = null;
for (int i = 1; i < elems.length; i++) {
if (i != elems.length - 1) {
path.append(elems[i]);
path.append(File.separator);
file = new File("D:" + File.separator + path.toString());
}
if (i == elems.length - 1) {
Pattern pattern = Pattern.compile("\\w+\\.[a-zA-Z]+");
Matcher matcher = pattern.matcher(elems[i]);
if ((matcher.matches())) {
if (!file.exists()) {
file.mkdirs();
}
String[] fileName = elems[i].split("\\.");
file = new File("D:" + File.separator + path.toString()
+ File.separator + fileName[0] + ".txt");
try {
file.createNewFile();
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file)));
writer.write(content);
writer.flush();
writer.close();
System.out.println("創(chuàng)建文件成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 獲取頁(yè)面的超鏈接并將其轉(zhuǎn)換為正式的A標(biāo)簽
*
* @param href
* @return
*/
public static String getHrefOfInOut(String href) {
/* 內(nèi)外部鏈接最終轉(zhuǎn)化為完整的鏈接格式 */
String resultHref = null;
/* 判斷是否為外部鏈接 */
if (href.startsWith("http://")) {
resultHref = href;
} else {
/* 如果是內(nèi)部鏈接,則補(bǔ)充完整的鏈接地址,其他的格式忽略不處理,如:a href="#" rel="external nofollow" */
if (href.startsWith("/")) {
result + href;
}
}
return resultHref;
}
/**
* 截取網(wǎng)頁(yè)網(wǎng)頁(yè)源文件的目標(biāo)內(nèi)容
*
* @param content
* @return
*/
public static String getGoalContent(String content) {
int sign = content.indexOf("<pre class=\"");
String signContent = content.substring(sign);
int start = signContent.indexOf(">");
int end = signContent.indexOf("</pre>");
return signContent.substring(start + 1, end);
}
/**
* 檢查網(wǎng)頁(yè)源文件中是否有目標(biāo)文件
*
* @param content
* @return
*/
public static int isHasGoalContent(String content) {
return content.indexOf("<pre class=\"");
}
}
HrefOfPage.java 此類(lèi)為獲取頁(yè)面的超鏈接
package com.sreach.spider;
/**
* @author binghe
*
*/
public class HrefOfPage {
/**
* 獲得頁(yè)面源代碼中超鏈接
*/
public static void getHrefOfContent(String content) {
System.out.println("開(kāi)始");
String[] contents = content.split("<a href=\"");
for (int i = 1; i < contents.length; i++) {
int endHref = contents[i].indexOf("\"");
String aHref = FunctionUtils.getHrefOfInOut(contents[i].substring(
0, endHref));
if (aHref != null) {
String href = FunctionUtils.getHrefOfInOut(aHref);
if (!UrlQueue.isContains(href)
&& href.indexOf("/code/explore") != -1
&& !VisitedUrlQueue.isContains(href)) {
UrlQueue.addElem(href);
}
}
}
System.out.println(UrlQueue.size() + "--抓取到的連接數(shù)");
System.out.println(VisitedUrlQueue.size() + "--已處理的頁(yè)面數(shù)");
}
}
UrlDataHanding.java 此類(lèi)主要是從未訪問(wèn)隊(duì)列中獲取url,下載頁(yè)面,分析url,保存已訪問(wèn)url等操作,實(shí)現(xiàn)Runnable接口
package com.sreach.spider;
/**
* @author binghe
*
*/
public class UrlDataHanding implements Runnable {
/**
* 下載對(duì)應(yīng)頁(yè)面并分析出頁(yè)面對(duì)應(yīng)的URL放在未訪問(wèn)隊(duì)列中。
*
* @param url
*/
public void dataHanding(String url) {
HrefOfPage.getHrefOfContent(DownloadPage.getContentFormUrl(url));
}
public void run() {
while (!UrlQueue.isEmpty()) {
dataHanding(UrlQueue.outElem());
}
}
}
UrlQueue.java 此類(lèi)主要是用來(lái)存放未訪問(wèn)的URL隊(duì)列
package com.sreach.spider;
import java.util.LinkedList;
/**
* @author binghe
*
*/
public class UrlQueue {
/** 超鏈接隊(duì)列 */
public static LinkedList<String> urlQueue = new LinkedList<String>();
/** 隊(duì)列中對(duì)應(yīng)最多的超鏈接數(shù)量 */
public static final int MAX_SIZE = 10000;
public synchronized static void addElem(String url) {
urlQueue.add(url);
}
public synchronized static String outElem() {
return urlQueue.removeFirst();
}
public synchronized static boolean isEmpty() {
return urlQueue.isEmpty();
}
public static int size() {
return urlQueue.size();
}
public static boolean isContains(String url) {
return urlQueue.contains(url);
}
}
VisitedUrlQueue.java 主要是保存已訪問(wèn)過(guò)的URL,使用HashSet來(lái)保存,主要是考慮到每個(gè)訪問(wèn)過(guò)的URL是不同。HashSet剛好符合這個(gè)要求
package com.sreach.spider;
import java.util.HashSet;
/**
* 已訪問(wèn)url隊(duì)列
* @author binghe
*
*/
public class VisitedUrlQueue {
public static HashSet<String> visitedUrlQueue = new HashSet<String>();
public synchronized static void addElem(String url) {
visitedUrlQueue.add(url);
}
public synchronized static boolean isContains(String url) {
return visitedUrlQueue.contains(url);
}
public synchronized static int size() {
return visitedUrlQueue.size();
}
}
Test.java 此類(lèi)為測(cè)試類(lèi)
import java.sql.SQLException;
import com.sreach.spider.UrlDataHanding;
import com.sreach.spider.UrlQueue;
/**
* @author binghe
*
*/
public class Test {
public static void main(String[] args) throws SQLException {
String url = "http://www.oschina.net/code/explore/achartengine/client/AndroidManifest.xml";
String url1 = "http://www.oschina.net/code/explore";
String url2 = "http://www.oschina.net/code/explore/achartengine";
String url3 = "http://www.oschina.net/code/explore/achartengine/client";
UrlQueue.addElem(url);
UrlQueue.addElem(url1);
UrlQueue.addElem(url2);
UrlQueue.addElem(url3);
UrlDataHanding[] url_Handings = new UrlDataHanding[10];
for (int i = 0; i < 10; i++) {
url_Handings[i] = new UrlDataHanding();
new Thread(url_Handings[i]).start();
}
}
}
說(shuō)明一下:由于我抓取的是針對(duì)oschina的,所以里面的url正則表達(dá)式不適合其他網(wǎng)站,需要自己修改一下。你也可以寫(xiě)成xml來(lái)配置。
到此這篇關(guān)于半小時(shí)實(shí)現(xiàn)Java手?jǐn)]網(wǎng)絡(luò)爬蟲(chóng)框架(附完整源碼)的文章就介紹到這了,更多相關(guān)Java 網(wǎng)絡(luò)爬蟲(chóng)框架內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- java編程實(shí)現(xiàn)簡(jiǎn)單的網(wǎng)絡(luò)爬蟲(chóng)示例過(guò)程
- Java 使用maven實(shí)現(xiàn)Jsoup簡(jiǎn)單爬蟲(chóng)案例詳解
- Java 實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲(chóng)框架詳細(xì)代碼
- 使用java實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲(chóng)
- Java實(shí)現(xiàn)的爬蟲(chóng)抓取圖片并保存操作示例
- java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的網(wǎng)絡(luò)爬蟲(chóng)代碼示例
- java實(shí)現(xiàn)網(wǎng)頁(yè)爬蟲(chóng)的示例講解
- java實(shí)現(xiàn)簡(jiǎn)單的爬蟲(chóng)之今日頭條
- Java爬蟲(chóng) 信息抓取的實(shí)現(xiàn)
- Java實(shí)現(xiàn)爬蟲(chóng)
相關(guān)文章
Spring Boot配置讀取實(shí)現(xiàn)方法解析
這篇文章主要介紹了Spring Boot配置讀取實(shí)現(xiàn)方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
springboot實(shí)現(xiàn)登錄功能的完整步驟
這篇文章主要給大家介紹了關(guān)于springboot實(shí)現(xiàn)登錄功能的完整步驟,在web應(yīng)用程序中,用戶登錄權(quán)限驗(yàn)證是非常重要的一個(gè)步驟,文中通過(guò)代碼以及圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09
解決springboot啟動(dòng)成功,但訪問(wèn)404的問(wèn)題
這篇文章主要介紹了解決springboot啟動(dòng)成功,但訪問(wèn)404的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
Java網(wǎng)絡(luò)編程之IO模型阻塞與非阻塞簡(jiǎn)要分析
這篇文章主要介紹Java網(wǎng)絡(luò)編程中的IO模型阻塞與非阻塞簡(jiǎn)要分析,文中附有示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09
SpringBoot+Tess4j實(shí)現(xiàn)牛的OCR識(shí)別工具的示例代碼
這篇文章主要介紹了SpringBoot+Tess4j實(shí)現(xiàn)牛的OCR識(shí)別工具的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Spring Boot利用@Async異步調(diào)用:使用Future及定義超時(shí)詳解
這篇文章主要給大家介紹了關(guān)于Spring Boot利用@Async異步調(diào)用:使用Future及定義超時(shí)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2018-05-05
java用兩個(gè)例子充分闡述多態(tài)的可拓展性介紹
下面小編就為大家?guī)?lái)一篇java用兩個(gè)例子充分闡述多態(tài)的可拓展性介紹。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06

