java搜索---網絡爬蟲實現


搜索方面的東西,需要了解網絡爬蟲方面的知識

首先介紹每個類的功能

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

FunctionUtils.java 的功能是提供不同的靜態方法,包括:頁面鏈接正則表達式匹配,獲取URL鏈接的元素,判斷是否創建文件,獲取頁面的Url並將其轉換為規范的Url,截取網頁網頁源文件的目標內容。

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

UrlDataHanding.java 的功能是整合各個給類,實現url到獲取數據到數據處理類。

UrlQueue.java 的未訪問Url隊列。

VisitedUrlQueue.java 已訪問過的URL隊列。

下面介紹一下每個類的源代碼:

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.       * 根據URL抓取網頁內容  
  18.       *   
  19.       * @param url  
  20.       * @return  
  21.       */ 
  22.      public static String getContentFormUrl(String url)  
  23.      {  
  24.          /* 實例化一個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.                  /* 轉化為文本信息 */ 
  42.                  content = EntityUtils.toString(entity);  
  43.    
  44.                  /* 判斷是否符合下載網頁源代碼到本地的條件 */ 
  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.      * 匹配超鏈接的正則表達式  
  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.      * 判斷是否創建文件  
  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.      * 創建對應文件  
  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("創建文件成功");  
  99.                     } catch (IOException e)  
  100.                     {  
  101.                         e.printStackTrace();  
  102.                     }  
  103.  
  104.                 }  
  105.             }  
  106.  
  107.         }  
  108.     }  
  109.  
  110.     /**  
  111.      * 獲取頁面的超鏈接並將其轉換為正式的A標簽  
  112.      *   
  113.      * @param href  
  114.      * @return  
  115.      */ 
  116.     public static String getHrefOfInOut(String href)  
  117.     {  
  118.         /* 內外部鏈接最終轉化為完整的鏈接格式 */ 
  119.         String resultHref = null;  
  120.  
  121.         /* 判斷是否為外部鏈接 */ 
  122.         if (href.startsWith("http://"))  
  123.         {  
  124.             resultHref = href;  
  125.         } else 
  126.         {  
  127.             /* 如果是內部鏈接,則補充完整的鏈接地址,其他的格式忽略不處理,如:a href="#" */ 
  128.             if (href.startsWith("/"))  
  129.             {  
  130.                 resultHref = "http://www.oschina.net" + href;  
  131.             }  
  132.         }  
  133.  
  134.         return resultHref;  
  135.     }  
  136.  
  137.     /**  
  138.      * 截取網頁網頁源文件的目標內容  
  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.      * 檢查網頁源文件中是否有目標文件  
  156.      *   
  157.      * @param content  
  158.      * @return  
  159.      */ 
  160.     public static int isHasGoalContent(String content)  
  161.     {  
  162.         return content.indexOf("<pre class=\"");  
  163.     }  
  164.  
  165. 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() + "--抓取到的連接數");  
    35.         System.out.println(VisitedUrlQueue.size() + "--已處理的頁面數");  
    36.  
    37.     }  
    38.  

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

        
        
        
                
    1. View Code   
    2.  
    3. package com.sreach.spider;  
    4.  
    5. public class UrlDataHanding implements Runnable  
    6. {  
    7.     /**  
    8.      * 下載對應頁面並分析出頁面對應的URL放在未訪問隊列中。  
    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隊列

        
        
        
                
    1. View Code   
    2.  
    3. package com.sreach.spider;  
    4.  
    5. import java.util.LinkedList;  
    6.  
    7. public class UrlQueue  
    8. {  
    9.     /**超鏈接隊列*/ 
    10.     public static LinkedList<String> urlQueue = new LinkedList<String>();  
    11.       
    12.     /**隊列中對應最多的超鏈接數量*/ 
    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來保存,主要是考慮到每個訪問過的URL是不同。HashSet剛好符合這個要求

        
        
        
                
    1. View Code   
    2.  
    3. package com.sreach.spider;  
    4.  
    5. import java.util.HashSet;  
    6.  
    7. /**  
    8.  * 已訪問url隊列  
    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正則表達式不適合其他網站,需要自己修改一下。你也可以寫成xml來配置。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM