成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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

開發(fā) 后端
最近在學(xué)習(xí)搜索方面的東西,需要了解網(wǎng)絡(luò)爬蟲方面的知識,雖然有很多開源的強(qiáng)大的爬蟲,但本著學(xué)習(xí)的態(tài)度,自己寫了一個(gè)簡單的網(wǎng)絡(luò)爬蟲,以便了解其中原理。

最近在學(xué)習(xí)搜索方面的東西,需要了解網(wǎng)絡(luò)爬蟲方面的知識,雖然有很多開源的強(qiáng)大的爬蟲,但本著學(xué)習(xí)的態(tài)度,自己寫了一個(gè)簡單的網(wǎng)絡(luò)爬蟲,以便了解其中原理。

首先介紹每個(gè)類的功能

DownloadPage.java的功能是下載此超鏈接的頁面源代碼.

FunctionUtils.java 的功能是提供不同的靜態(tài)方法,包括:頁面鏈接正則表達(dá)式匹配,獲取URL鏈接的元素,判斷是否創(chuàng)建文件,獲取頁面的Url并將其轉(zhuǎn)換為規(guī)范的Url,截取網(wǎng)頁網(wǎng)頁源文件的目標(biāo)內(nèi)容。

HrefOfPage.java 的功能是獲取頁面源代碼的超鏈接。

UrlDataHanding.java 的功能是整合各個(gè)給類,實(shí)現(xiàn)url到獲取數(shù)據(jù)到數(shù)據(jù)處理類。

UrlQueue.java 的未訪問Url隊(duì)列。

VisitedUrlQueue.java 已訪問過的URL隊(duì)列。

下面介紹一下每個(gè)類的源代碼:

DownloadPage.java 此類要用到HttpClient組件。

  1. View Code   
  2.  package com.sreach.spider;  
  3.    
  4.  import java.io.IOException;  
  5.  import org.apache.http.HttpEntity;  
  6.  import org.apache.http.HttpResponse;  
  7.  import org.apache.http.client.ClientProtocolException;  
  8.  import org.apache.http.client.HttpClient;  
  9.  import org.apache.http.client.methods.HttpGet;  
  10.  import org.apache.http.impl.client.DefaultHttpClient;  
  11.  import org.apache.http.util.EntityUtils;  
  12.    
  13.  public class DownloadPage  
  14.  {  
  15.    
  16.      /**  
  17.       * 根據(jù)URL抓取網(wǎng)頁內(nèi)容  
  18.       *   
  19.       * @param url  
  20.       * @return  
  21.       */ 
  22.      public static String getContentFormUrl(String url)  
  23.      {  
  24.          /* 實(shí)例化一個(gè)HttpClient客戶端 */ 
  25.          HttpClient client = new DefaultHttpClient();  
  26.          HttpGet getHttp = new HttpGet(url);  
  27.    
  28.          String content = null;  
  29.    
  30.          HttpResponse response;  
  31.          try 
  32.          {  
  33.              /*獲得信息載體*/ 
  34.              response = client.execute(getHttp);  
  35.              HttpEntity entity = response.getEntity();  
  36.    
  37.              VisitedUrlQueue.addElem(url);  
  38.    
  39.              if (entity != null)  
  40.              {  
  41.                  /* 轉(zhuǎn)化為文本信息 */ 
  42.                  content = EntityUtils.toString(entity);  
  43.    
  44.                  /* 判斷是否符合下載網(wǎng)頁源代碼到本地的條件 */ 
  45.                  if (FunctionUtils.isCreateFile(url)  
  46.                          && FunctionUtils.isHasGoalContent(content) != -1)  
  47.                  {  
  48.                      FunctionUtils.createFile(FunctionUtils  
  49.                              .getGoalContent(content), url);  
  50.                  }  
  51.              }  
  52.    
  53.          } catch (ClientProtocolException e)  
  54.          {  
  55.              e.printStackTrace();  
  56.          } catch (IOException e)  
  57.          {  
  58.              e.printStackTrace();  
  59.          } finally 
  60.          {  
  61.              client.getConnectionManager().shutdown();  
  62.          }  
  63.            
  64.          return content;  
  65.      }  
  66.    
  67.  } 

FunctionUtils.java 此類的方法均為static方法

  1. View Code   
  2.  
  3. package com.sreach.spider;  
  4.  
  5. import java.io.BufferedWriter;  
  6. import java.io.File;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.OutputStreamWriter;  
  10. import java.util.regex.Matcher;  
  11. import java.util.regex.Pattern;  
  12.  
  13. public class FunctionUtils  
  14. {  
  15.  
  16.     /**  
  17.      * 匹配超鏈接的正則表達(dá)式  
  18.      */ 
  19.     private static String pat = "http://www\\.oschina\\.net/code/explore/.*/\\w+\\.[a-zA-Z]+";  
  20.     private static Pattern pattern = Pattern.compile(pat);  
  21.  
  22.     private static BufferedWriter writer = null;  
  23.  
  24.     /**  
  25.      * 爬蟲搜索深度  
  26.      */ 
  27.     public static int depth = 0;  
  28.  
  29.     /**  
  30.      * 以"/"來分割URL,獲得超鏈接的元素  
  31.      *   
  32.      * @param url  
  33.      * @return  
  34.      */ 
  35.     public static String[] divUrl(String url)  
  36.     {  
  37.         return url.split("/");  
  38.     }  
  39.  
  40.     /**  
  41.      * 判斷是否創(chuàng)建文件  
  42.      *   
  43.      * @param url  
  44.      * @return  
  45.      */ 
  46.     public static boolean isCreateFile(String url)  
  47.     {  
  48.         Matcher matcher = pattern.matcher(url);  
  49.  
  50.         return matcher.matches();  
  51.     }  
  52.  
  53.     /**  
  54.      * 創(chuàng)建對應(yīng)文件  
  55.      *   
  56.      * @param content  
  57.      * @param urlPath  
  58.      */ 
  59.     public static void createFile(String content, String urlPath)  
  60.     {  
  61.         /* 分割url */ 
  62.         String[] elems = divUrl(urlPath);  
  63.         StringBuffer path = new StringBuffer();  
  64.  
  65.         File file = null;  
  66.         for (int i = 1; i < elems.length; i++)  
  67.         {  
  68.             if (i != elems.length - 1)  
  69.             {  
  70.  
  71.                 path.append(elems[i]);  
  72.                 path.append(File.separator);  
  73.                 file = new File("D:" + File.separator + path.toString());  
  74.  
  75.             }  
  76.  
  77.             if (i == elems.length - 1)  
  78.             {  
  79.                 Pattern pattern = Pattern.compile("\\w+\\.[a-zA-Z]+");  
  80.                 Matcher matcher = pattern.matcher(elems[i]);  
  81.                 if ((matcher.matches()))  
  82.                 {  
  83.                     if (!file.exists())  
  84.                     {  
  85.                         file.mkdirs();  
  86.                     }  
  87.                     String[] fileName = elems[i].split("\\.");  
  88.                     file = new File("D:" + File.separator + path.toString()  
  89.                             + File.separator + fileName[0] + ".txt");  
  90.                     try 
  91.                     {  
  92.                         file.createNewFile();  
  93.                         writer = new BufferedWriter(new OutputStreamWriter(  
  94.                                 new FileOutputStream(file)));  
  95.                         writer.write(content);  
  96.                         writer.flush();  
  97.                         writer.close();  
  98.                         System.out.println("創(chuàng)建文件成功");  
  99.                     } catch (IOException e)  
  100.                     {  
  101.                         e.printStackTrace();  
  102.                     }  
  103.  
  104.                 }  
  105.             }  
  106.  
  107.         }  
  108.     }  
  109.  
  110.     /**  
  111.      * 獲取頁面的超鏈接并將其轉(zhuǎn)換為正式的A標(biāo)簽  
  112.      *   
  113.      * @param href  
  114.      * @return  
  115.      */ 
  116.     public static String getHrefOfInOut(String href)  
  117.     {  
  118.         /* 內(nèi)外部鏈接最終轉(zhuǎn)化為完整的鏈接格式 */ 
  119.         String resultHref = null;  
  120.  
  121.         /* 判斷是否為外部鏈接 */ 
  122.         if (href.startsWith("http://"))  
  123.         {  
  124.             resultHref = href;  
  125.         } else 
  126.         {  
  127.             /* 如果是內(nèi)部鏈接,則補(bǔ)充完整的鏈接地址,其他的格式忽略不處理,如:a href="#" */ 
  128.             if (href.startsWith("/"))  
  129.             {  
  130.                 resultHref = "http://www.oschina.net" + href;  
  131.             }  
  132.         }  
  133.  
  134.         return resultHref;  
  135.     }  
  136.  
  137.     /**  
  138.      * 截取網(wǎng)頁網(wǎng)頁源文件的目標(biāo)內(nèi)容  
  139.      *   
  140.      * @param content  
  141.      * @return  
  142.      */ 
  143.     public static String getGoalContent(String content)  
  144.     {  
  145.         int sign = content.indexOf("<pre class=\"");  
  146.         String signContent = content.substring(sign);  
  147.  
  148.         int start = signContent.indexOf(">");  
  149.         int end = signContent.indexOf("</pre>");  
  150.  
  151.         return signContent.substring(start + 1, end);  
  152.     }  
  153.  
  154.     /**  
  155.      * 檢查網(wǎng)頁源文件中是否有目標(biāo)文件  
  156.      *   
  157.      * @param content  
  158.      * @return  
  159.      */ 
  160.     public static int isHasGoalContent(String content)  
  161.     {  
  162.         return content.indexOf("<pre class=\"");  
  163.     }  
  164.  

#p#

HrefOfPage.java 此類為獲取頁面的超鏈接

  1. View Code   
  2.  
  3. package com.sreach.spider;  
  4.  
  5. public class HrefOfPage  
  6. {  
  7.     /**  
  8.      * 獲得頁面源代碼中超鏈接  
  9.      */ 
  10.     public static void getHrefOfContent(String content)  
  11.     {  
  12.         System.out.println("開始");  
  13.         String[] contents = content.split("<a href=\"");  
  14.         for (int i = 1; i < contents.length; i++)  
  15.         {  
  16.             int endHref = contents[i].indexOf("\"");  
  17.  
  18.             String aHref = FunctionUtils.getHrefOfInOut(contents[i].substring(  
  19. , endHref));  
  20.  
  21.             if (aHref != null)  
  22.             {  
  23.                 String href = FunctionUtils.getHrefOfInOut(aHref);  
  24.  
  25.                 if (!UrlQueue.isContains(href)  
  26.                         && href.indexOf("/code/explore") != -1 
  27.                         && !VisitedUrlQueue.isContains(href))  
  28.                 {  
  29.                     UrlQueue.addElem(href);  
  30.                 }  
  31.             }  
  32.         }  
  33.  
  34.         System.out.println(UrlQueue.size() + "--抓取到的連接數(shù)");  
  35.         System.out.println(VisitedUrlQueue.size() + "--已處理的頁面數(shù)");  
  36.  
  37.     }  
  38.  

UrlDataHanding.java 此類主要是從未訪問隊(duì)列中獲取url,下載頁面,分析url,保存已訪問url等操作,實(shí)現(xiàn)Runnable接口

  1. View Code   
  2.  
  3. package com.sreach.spider;  
  4.  
  5. public class UrlDataHanding implements Runnable  
  6. {  
  7.     /**  
  8.      * 下載對應(yīng)頁面并分析出頁面對應(yīng)的URL放在未訪問隊(duì)列中。  
  9.      * @param url  
  10.      */ 
  11.     public void dataHanding(String url)  
  12.     {  
  13.             HrefOfPage.getHrefOfContent(DownloadPage.getContentFormUrl(url));  
  14.     }  
  15.           
  16.     public void run()  
  17.     {  
  18.         while(!UrlQueue.isEmpty())  
  19.         {  
  20.            dataHanding(UrlQueue.outElem());  
  21.         }  
  22.     }  

UrlQueue.java 此類主要是用來存放未訪問的URL隊(duì)列

  1. View Code   
  2.  
  3. package com.sreach.spider;  
  4.  
  5. import java.util.LinkedList;  
  6.  
  7. public class UrlQueue  
  8. {  
  9.     /**超鏈接隊(duì)列*/ 
  10.     public static LinkedList<String> urlQueue = new LinkedList<String>();  
  11.       
  12.     /**隊(duì)列中對應(yīng)最多的超鏈接數(shù)量*/ 
  13.     public static final int MAX_SIZE = 10000;  
  14.       
  15.     public synchronized static void addElem(String url)  
  16.     {  
  17.         urlQueue.add(url);  
  18.     }  
  19.       
  20.     public synchronized static String outElem()  
  21.     {  
  22.         return urlQueue.removeFirst();  
  23.     }  
  24.       
  25.     public synchronized static boolean isEmpty()  
  26.     {  
  27.         return urlQueue.isEmpty();  
  28.     }  
  29.       
  30.     public  static int size()  
  31.     {  
  32.         return urlQueue.size();  
  33.     }  
  34.       
  35.     public  static boolean isContains(String url)  
  36.     {  
  37.         return urlQueue.contains(url);  
  38.     }  
  39.  

VisitedUrlQueue.java 主要是保存已訪問過的URL,使用HashSet來保存,主要是考慮到每個(gè)訪問過的URL是不同。HashSet剛好符合這個(gè)要求

  1. View Code   
  2.  
  3. package com.sreach.spider;  
  4.  
  5. import java.util.HashSet;  
  6.  
  7. /**  
  8.  * 已訪問url隊(duì)列  
  9.  * @author HHZ  
  10.  *  
  11.  */ 
  12. public class VisitedUrlQueue  
  13. {  
  14.     public static HashSet<String> visitedUrlQueue = new HashSet<String>();  
  15.  
  16.     public synchronized static void addElem(String url)  
  17.     {  
  18.         visitedUrlQueue.add(url);  
  19.     }  
  20.  
  21.     public synchronized static boolean isContains(String url)  
  22.     {  
  23.         return visitedUrlQueue.contains(url);  
  24.     }  
  25.  
  26.     public synchronized static int size()  
  27.     {  
  28.         return visitedUrlQueue.size();  
  29.     }  

Test.java 此類為測試類

  1. View Code   
  2.  
  3. import java.sql.SQLException;  
  4.  
  5. import com.sreach.spider.UrlDataHanding;  
  6. import com.sreach.spider.UrlQueue;  
  7.  
  8. public class Test  
  9. {  
  10.   public static void main(String[] args) throws SQLException  
  11.   {  
  12.       String url = "http://www.oschina.net/code/explore/achartengine/client/AndroidManifest.xml";  
  13.       String url1 = "http://www.oschina.net/code/explore";  
  14.       String url2 = "http://www.oschina.net/code/explore/achartengine";  
  15.       String url3 = "http://www.oschina.net/code/explore/achartengine/client";  
  16.         
  17.         
  18.       UrlQueue.addElem(url);  
  19.       UrlQueue.addElem(url1);  
  20.       UrlQueue.addElem(url2);  
  21.       UrlQueue.addElem(url3);  
  22.         
  23.       UrlDataHanding[] url_Handings = new UrlDataHanding[10];  
  24.         
  25.           for(int i = 0 ; i < 10 ; i++)  
  26.           {  
  27.               url_Handings[i] = new UrlDataHanding();  
  28.               new Thread(url_Handings[i]).start();  
  29.           }  
  30.  
  31.   }  

說明一下:由于我抓取的是針對oschina的,所以里面的url正則表達(dá)式不適合其他網(wǎng)站,需要自己修改一下。你也可以寫成xml來配置。

小弟技術(shù)有限,有些地方確實(shí)寫得不好,希望各位大牛不吝指教。

原文鏈接:http://www.cnblogs.com/HZhoog/archive/2012/05/08/2490374.html

【編輯推薦】

  1. Java調(diào)用SQL Server的存儲過程詳解
  2. MongoDB、Java與對象關(guān)系映射
  3. Java的Comparable接口的一個(gè)陷阱
  4. Apache CXF實(shí)戰(zhàn)之三:傳輸Java對象
  5. Java程序設(shè)計(jì):圖形與多媒體處理

 

責(zé)任編輯:林師授 來源: HZhoog的博客
相關(guān)推薦

2011-03-09 10:07:56

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

2011-03-18 10:25:20

javac++Python

2017-08-09 15:27:33

python爬蟲開發(fā)工具

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ò)爬蟲

2011-07-04 10:04:52

java網(wǎng)絡(luò)程序

2024-04-30 09:33:00

JavaScriptPythonexecjs

2018-05-14 15:27:06

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

2023-06-01 13:15:23

2022-09-20 07:02:20

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

2022-08-30 08:00:54

日志MDC哈希表

2019-10-18 08:52:41

程序員爬蟲Java

2024-03-08 12:17:39

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

2018-01-30 18:15:12

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

2023-11-27 08:51:46

PythonRequests庫

2022-12-29 12:06:28

2012-02-01 11:20:23

Java線程

2024-11-27 06:31:02

2019-10-08 16:35:53

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

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

主站蜘蛛池模板: av特级毛片| 中文字幕亚洲精品 | 波多野结衣一区二区 | 九九综合九九 | 久久九九99 | 午夜免费精品视频 | 久久精品免费观看 | 欧美日韩国产一区二区三区 | 精品久久久久久久久久久 | 91精品久久久久久久久中文字幕 | 91中文字幕在线观看 | 久久久精品一区 | 国产一区二区三区在线 | 在线看国产 | 日韩淫片免费看 | 国产1区2区在线观看 | 成人精品一区二区户外勾搭野战 | 免费看的黄网站 | 视频一区 国产精品 | 久久高清| 国产a一区二区 | 久久99一区二区 | 日韩一区二区三区精品 | 国产免费一区二区三区网站免费 | 人人看人人搞 | 日韩在线小视频 | 2022精品国偷自产免费观看 | 四虎在线观看 | 日韩欧美三区 | 午夜在线免费观看 | www.av在线| 欧美一区二区三区在线观看视频 | 成人在线电影在线观看 | 亚洲精品日韩视频 | 欧美性受xxxx白人性爽 | 天天爱爱网 | 日本精品一区二区三区在线观看视频 | 国产一区二区不卡 | 久久曰视频 | 三级欧美 | 美女国产一区 |