自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java網(wǎng)絡(luò)爬蟲的實(shí)現(xiàn)

開發(fā) 后端
記得在剛找工作時(shí),隔壁的一位同學(xué)在面試時(shí)豪言壯語曾實(shí)現(xiàn)過網(wǎng)絡(luò)爬蟲,當(dāng)時(shí)的景仰之情猶如滔滔江水連綿不絕。后來,在做圖片搜索時(shí),需要大量的測試圖片,因此萌生了從Amazon中爬取圖書封面圖片的想法,從網(wǎng)上也吸取了一些前人的經(jīng)驗(yàn),實(shí)現(xiàn)了一個(gè)簡單但足夠用的爬蟲系統(tǒng)。

記得在剛找工作時(shí),隔壁的一位同學(xué)在面試時(shí)豪言壯語曾實(shí)現(xiàn)過網(wǎng)絡(luò)爬蟲,當(dāng)時(shí)的景仰之情猶如滔滔江水連綿不絕。后來,在做圖片搜索時(shí),需要大量的測試圖片,因此萌生了從Amazon中爬取圖書封面圖片的想法,從網(wǎng)上也吸取了一些前人的經(jīng)驗(yàn),實(shí)現(xiàn)了一個(gè)簡單但足夠用的爬蟲系統(tǒng)。

網(wǎng)絡(luò)爬蟲是一個(gè)自動(dòng)提取網(wǎng)頁的程序,它為搜索引擎從萬維網(wǎng)上下載網(wǎng)頁,是搜索引擎的重要組成,其基本架構(gòu)如下圖所示:

 

[[19805]]

 

傳統(tǒng)爬蟲從一個(gè)或若干初始網(wǎng)頁的URL開始,獲得初始網(wǎng)頁上的URL,在抓取網(wǎng)頁的過程中,不斷從當(dāng)前頁面上抽取新的URL放入隊(duì)列,直到滿足系統(tǒng)的一定停止條件。對(duì)于垂直搜索來說,聚焦爬蟲,即有針對(duì)性地爬取特定主題網(wǎng)頁的爬蟲,更為適合。

本文爬蟲程序的核心代碼如下:

Java代碼

 

 

  1. public void crawl() throws Throwable {     
  2.     while (continueCrawling()) {     
  3.         CrawlerUrl url = getNextUrl(); //獲取待爬取隊(duì)列中的下一個(gè)URL     
  4.         if (url != null) {     
  5.             printCrawlInfo();      
  6.             String content = getContent(url); //獲取URL的文本信息     
  7.                  
  8.             //聚焦爬蟲只爬取與主題內(nèi)容相關(guān)的網(wǎng)頁,這里采用正則匹配簡單處理     
  9.             if (isContentRelevant(content, this.regexpSearchPattern)) {     
  10.                 saveContent(url, content); //保存網(wǎng)頁至本地     
  11.     
  12.                 //獲取網(wǎng)頁內(nèi)容中的鏈接,并放入待爬取隊(duì)列中     
  13.                 Collection urlStrings = extractUrls(content, url);     
  14.                 addUrlsToUrlQueue(url, urlStrings);     
  15.             } else {     
  16.                 System.out.println(url + " is not relevant ignoring ...");     
  17.             }     
  18.     
  19.             //延時(shí)防止被對(duì)方屏蔽     
  20.             Thread.sleep(this.delayBetweenUrls);     
  21.         }     
  22.     }     
  23.     closeOutputStream();     
  24. }    

 

整個(gè)函數(shù)由getNextUrl、getContent、isContentRelevant、extractUrls、addUrlsToUrlQueue等幾個(gè)核心方法組成,下面將一一介紹。先看getNextUrl:

Java代碼

 

復(fù)制代碼

 

 

  1. private CrawlerUrl getNextUrl() throws Throwable {     
  2.     CrawlerUrl nextUrl = null;     
  3.     while ((nextUrl == null) && (!urlQueue.isEmpty())) {     
  4.         CrawlerUrl crawlerUrl = this.urlQueue.remove();     
  5.                     
  6.         //doWeHavePermissionToVisit:是否有權(quán)限訪問該URL,友好的爬蟲會(huì)根據(jù)網(wǎng)站提供的"Robot.txt"中配置的規(guī)則進(jìn)行爬取     
  7.         //isUrlAlreadyVisited:URL是否訪問過,大型的搜索引擎往往采用BloomFilter進(jìn)行排重,這里簡單使用HashMap     
  8.         //isDepthAcceptable:是否達(dá)到指定的深度上限。爬蟲一般采取廣度優(yōu)先的方式。一些網(wǎng)站會(huì)構(gòu)建爬蟲陷阱(自動(dòng)生成一些無效鏈接使爬蟲陷入死循環(huán)),采用深度限制加以避免     
  9.         if (doWeHavePermissionToVisit(crawlerUrl)     
  10.             && (!isUrlAlreadyVisited(crawlerUrl))      
  11.             && isDepthAcceptable(crawlerUrl)) {     
  12.             nextUrl = crawlerUrl;     
  13.             // System.out.println("Next url to be visited is " + nextUrl);     
  14.         }     
  15.     }     
  16.     return nextUrl;     
  17. }   

 

更多的關(guān)于robot.txt的具體寫法,可參考以下這篇文章:

http://www.bloghuman.com/post/67/

getContent內(nèi)部使用apache的httpclient 4.1獲取網(wǎng)頁內(nèi)容,具體代碼如下:

Java代碼

 

 

  1. private String getContent(CrawlerUrl url) throws Throwable {     
  2.     //HttpClient4.1的調(diào)用與之前的方式不同     
  3.     HttpClient client = new DefaultHttpClient();     
  4.     HttpGet httpGet = new HttpGet(url.getUrlString());     
  5.     StringBuffer strBuf = new StringBuffer();     
  6.     HttpResponse response = client.execute(httpGet);     
  7.     if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {     
  8.         HttpEntity entity = response.getEntity();     
  9.         if (entity != null) {     
  10.             BufferedReader reader = new BufferedReader(     
  11.                 new InputStreamReader(entity.getContent(), "UTF-8"));     
  12.             String line = null;     
  13.             if (entity.getContentLength() > 0) {     
  14.                 strBuf = new StringBuffer((int) entity.getContentLength());     
  15.                 while ((line = reader.readLine()) != null) {     
  16.                     strBuf.append(line);     
  17.                 }     
  18.             }     
  19.         }     
  20.         if (entity != null) {     
  21.             entity.consumeContent();     
  22.         }     
  23.     }     
  24.     //將url標(biāo)記為已訪問     
  25.     markUrlAsVisited(url);     
  26.     return strBuf.toString();     
  27. }    

 

對(duì)于垂直型應(yīng)用來說,數(shù)據(jù)的準(zhǔn)確性往往更為重要。聚焦型爬蟲的主要特點(diǎn)是,只收集和主題相關(guān)的數(shù)據(jù),這就是isContentRelevant方法的作用。這里或許要使用分類預(yù)測技術(shù),為簡單起見,采用正則匹配來代替。其主要代碼如下:

Java代碼

 

 

  1. public static boolean isContentRelevant(String content,     
  2. Pattern regexpPattern) {     
  3.     boolean retValue = false;     
  4.     if (content != null) {     
  5.         //是否符合正則表達(dá)式的條件     
  6.         Matcher m = regexpPattern.matcher(content.toLowerCase());     
  7.         retValue = m.find();     
  8.     }     
  9.     return retValue;     
  10. }    

 

extractUrls的主要作用,是從網(wǎng)頁中獲取更多的URL,包括內(nèi)部鏈接和外部鏈接,代碼如下:

Java代碼

 

 

  1. public List extractUrls(String text, CrawlerUrl crawlerUrl) {     
  2.     Map urlMap = new HashMap();     
  3.     extractHttpUrls(urlMap, text);     
  4.     extractRelativeUrls(urlMap, text, crawlerUrl);     
  5.     return new ArrayList(urlMap.keySet());     
  6. }     
  7.     
  8. //處理外部鏈接     
  9. private void extractHttpUrls(Map urlMap, String text) {     
  10.     Matcher m = httpRegexp.matcher(text);     
  11.     while (m.find()) {     
  12.         String url = m.group();     
  13.         String[] terms = url.split("a href=\"");     
  14.         for (String term : terms) {     
  15.             // System.out.println("Term = " + term);     
  16.             if (term.startsWith("http")) {     
  17.                 int index = term.indexOf("\"");     
  18.                 if (index > 0) {     
  19.                     term = term.substring(0, index);     
  20.                 }     
  21.                 urlMap.put(term, term);     
  22.                 System.out.println("Hyperlink: " + term);     
  23.             }     
  24.         }     
  25.     }     
  26. }     
  27.     
  28. //處理內(nèi)部鏈接     
  29. private void extractRelativeUrls(Map urlMap, String text,     
  30.         CrawlerUrl crawlerUrl) {     
  31.     Matcher m = relativeRegexp.matcher(text);     
  32.     URL textURL = crawlerUrl.getURL();     
  33.     String host = textURL.getHost();     
  34.     while (m.find()) {     
  35.         String url = m.group();     
  36.         String[] terms = url.split("a href=\"");     
  37.         for (String term : terms) {     
  38.             if (term.startsWith("/")) {     
  39.                 int index = term.indexOf("\"");     
  40.                 if (index > 0) {     
  41.                     term = term.substring(0, index);     
  42.                 }     
  43.                 String s = "http://" + host + term;     
  44.                 urlMap.put(s, s);     
  45.                 System.out.println("Relative url: " + s);     
  46.             }     
  47.         }     
  48.     }     
  49.     
  50. }    

 

如此,便構(gòu)建了一個(gè)簡單的網(wǎng)絡(luò)爬蟲程序,可以使用以下程序來測試它:

Java代碼

 

 

  1. public static void main(String[] args) {     
  2.     try {     
  3.         String url = "http://www.amazon.com";     
  4.         Queue urlQueue = new LinkedList();     
  5.         String regexp = "java";     
  6.         urlQueue.add(new CrawlerUrl(url, 0));     
  7.         NaiveCrawler crawler = new NaiveCrawler(urlQueue, 1005, 1000L,     
  8.                 regexp);     
  9.         // boolean allowCrawl = crawler.areWeAllowedToVisit(url);     
  10.         // System.out.println("Allowed to crawl: " + url + " " +     
  11.         // allowCrawl);     
  12.         crawler.crawl();     
  13.     } catch (Throwable t) {     
  14.         System.out.println(t.toString());     
  15.         t.printStackTrace();     
  16.     }     
  17. }    

 

當(dāng)然,你可以為它賦予更為高級(jí)的功能,比如多線程、更智能的聚焦、結(jié)合Lucene建立索引等等。更為復(fù)雜的情況,可以考慮使用一些開源的蜘蛛程序,比如Nutch或是Heritrix等等,就不在本文的討論范圍了。

【編輯推薦】

  1. Java創(chuàng)始人:Oracle起訴Google與版權(quán)無關(guān)
  2. 薪酬與權(quán)力 Java之父講述離職Oracle內(nèi)幕
  3. Java之父:我們看中的并非Java語言,而是JVM
  4. 2010年10月編程語言排行榜:Java的混亂之治
責(zé)任編輯:金賀 來源: JavaEye博客
相關(guān)推薦

2012-05-10 13:42:26

Java網(wǎng)絡(luò)爬蟲

2017-05-16 15:33:42

Python網(wǎng)絡(luò)爬蟲核心技術(shù)框架

2018-02-23 14:30:13

2010-04-20 11:40:52

網(wǎng)絡(luò)爬蟲

2024-04-30 09:33:00

JavaScriptPythonexecjs

2018-05-14 15:27:06

Python網(wǎng)絡(luò)爬蟲爬蟲架構(gòu)

2019-10-18 08:52:41

程序員爬蟲Java

2023-06-01 13:15:23

2024-03-08 12:17:39

網(wǎng)絡(luò)爬蟲Python開發(fā)

2018-01-30 18:15:12

Python網(wǎng)絡(luò)爬蟲gevent

2022-09-20 07:02:20

網(wǎng)絡(luò)爬蟲反爬蟲

2024-11-27 06:31:02

2023-11-27 08:51:46

PythonRequests庫

2012-06-13 17:38:57

2019-10-08 16:35:53

Java網(wǎng)絡(luò)爬蟲webmagic

2011-03-18 10:25:20

javac++Python

2024-11-22 16:06:21

2024-07-02 11:32:38

2016-08-18 00:21:12

網(wǎng)絡(luò)爬蟲抓取網(wǎng)絡(luò)

2019-06-11 09:06:22

網(wǎng)絡(luò)爬蟲工具
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)