Java爬虫搜索原理实现

没事做,又研究了一下爬虫搜索,两三天时间总算是把原理闹的差不多了,基本实现了爬虫搜索的原理,本次实现还是俩程序,分别是按广度优先和深度优先完成的,广度优先没啥问题,深度优先请慎用,有极大的概率会造成死循环情况,下面深度优先的测试网站就造成了死循环。。。。好吧,我承认是我人品不太好。。。下面有请代码君出场~~~~~~~~~~~~~~~

1.广度优先

[java]  view plain copy
  1. /** 
  2.  * 完成广度优先搜索 
  3.  */  
  4. package net.meteor.java;  
  5.   
  6. import java.io.BufferedReader;  
  7. import java.io.FileInputStream;  
  8. import java.io.FileOutputStream;  
  9. import java.io.FileWriter;  
  10. import java.io.IOException;  
  11. import java.io.InputStream;  
  12. import java.io.InputStreamReader;  
  13. import java.net.HttpURLConnection;  
  14. import java.net.URL;  
  15. import java.util.regex.Matcher;  
  16. import java.util.regex.Pattern;  
  17.   
  18. /** 
  19.  * @author 魏诗尧 
  20.  * @version 1.8 
  21.  * @emali inwsy@hotmail.com 
  22.  */  
  23. public class SearchCrawlerBreadth {  
  24.   
  25.     // 将网页源码下载到本地  
  26.     private void downHTML(String urlstr, String htmltxt) {  
  27.         // 声明链接  
  28.         HttpURLConnection con = null;  
  29.         // 声明输入流  
  30.         InputStream in = null;  
  31.         // 声明输出流  
  32.         FileOutputStream out = null;  
  33.   
  34.         try {  
  35.             // 实例化url  
  36.             URL url = new URL(urlstr);  
  37.             // 打开链接  
  38.             con = (HttpURLConnection) url.openConnection();  
  39.   
  40.             con.connect();  
  41.             // 打开输入流  
  42.             in = con.getInputStream();  
  43.             // 打开输出流创建接收文件  
  44.             out = new FileOutputStream(htmltxt);  
  45.   
  46.             byte[] b = new byte[1024];  
  47.   
  48.             int len = 0;  
  49.             // 将文件写入接收文件  
  50.             while ((len = in.read(b, 01024)) != -1) {  
  51.                 out.write(b, 0, len);  
  52.             }  
  53.             // 开始第二次爬行  
  54.             new SearchCrawlerBreadth().readTxt("src/href.txt");  
  55.   
  56.         } catch (Exception e) {  
  57.             System.out.println("未知主机!!");  
  58.         } finally {  
  59.             try {  
  60.                 // 关闭流  
  61.                 if (out != null)  
  62.                     out.close();  
  63.                 if (in != null)  
  64.                     in.close();  
  65.   
  66.             } catch (Exception e) {  
  67.   
  68.                 e.printStackTrace();  
  69.             }  
  70.         }  
  71.     }  
  72.   
  73.     // 页面解析  
  74.     private void readTxt(String hreftxt) {  
  75.         // 声明输入流  
  76.         InputStream in = null;  
  77.         FileWriter file = null;  
  78.         BufferedReader br = null;  
  79.   
  80.         try {  
  81.             // 实例化IO流,允许文件追加写  
  82.             file = new FileWriter(hreftxt, true);  
  83.   
  84.             in = new FileInputStream("src/html.txt");  
  85.   
  86.             br = new BufferedReader(new InputStreamReader(in));  
  87.             // 开始解析html  
  88.             while (br.readLine() != null) {  
  89.   
  90.                 String line = br.readLine();  
  91.                 // 创建正则表达式  
  92.                 Pattern pattern = Pattern.compile(  
  93.                         "<a\\s+href\\s*=\\s*\"?(.*?)[\"|>]",  
  94.                         Pattern.CASE_INSENSITIVE);  
  95.                 // 创建匹配器  
  96.                 Matcher matcher = pattern.matcher(line);  
  97.                 // 开始与正则表达式进行匹配  
  98.                 while (matcher.find()) {  
  99.                     String str = matcher.group(1);  
  100.                     // 跳过链到本页面内链接和无效链接  
  101.                     if (str.length() < 1) {  
  102.                         continue;  
  103.                     }  
  104.   
  105.                     if (str.charAt(0) == '#') {  
  106.                         continue;  
  107.                     }  
  108.   
  109.                     if (str.startsWith("/")) {  
  110.                         continue;  
  111.                     }  
  112.                       
  113.                     if (str.indexOf("mailto:") != -1) {  
  114.                         continue;  
  115.                     }  
  116.                     if (str.toLowerCase().indexOf("javascript") != -1) {  
  117.                         continue;  
  118.                     }  
  119.   
  120.                     if (str.startsWith("'")) {  
  121.                         continue;  
  122.                     }  
  123.                     // 将有效链接打印到屏幕  
  124.                     System.out.println(str);  
  125.                     // 将有效链接写入到文件  
  126.                     file.write(str + "\r\n");  
  127.   
  128.                 }  
  129.   
  130.             }  
  131.   
  132.         } catch (Exception e) {  
  133.             System.out.println("无效链接!!");  
  134.         } finally {  
  135.             // 关闭IO流  
  136.             try {  
  137.                 if (file != null)  
  138.                     file.close();  
  139.                 if (br != null)  
  140.                     br.close();  
  141.                 if (in != null)  
  142.                     in.close();  
  143.             } catch (Exception e) {  
  144.   
  145.                 e.printStackTrace();  
  146.             }  
  147.         }  
  148.     }  
  149.   
  150.     // 进行深度搜索  
  151.     private void search() {  
  152.         // 声明IO流  
  153.         InputStream in = null;  
  154.   
  155.         BufferedReader br = null;  
  156.   
  157.         try {  
  158.             // 实例化IO流  
  159.   
  160.             in = new FileInputStream("src/href.txt");  
  161.             br = new BufferedReader(new InputStreamReader(in));  
  162.             // 创建SearchCrawler的对象  
  163.             SearchCrawlerBreadth sc = new SearchCrawlerBreadth();  
  164.             // 开始按行读取有效链接的文件  
  165.             while (br.readLine() != null) {  
  166.                 String line = br.readLine();  
  167.                 // 递归调用爬虫爬行页面  
  168.                 sc.downHTML(line, "src/html.txt");  
  169.             }  
  170.   
  171.         } catch (IOException e) {  
  172.   
  173.             e.printStackTrace();  
  174.   
  175.         } finally {  
  176.             try {  
  177.                 // 关闭流  
  178.                 if (br != null)  
  179.                     br.close();  
  180.                 if (in != null)  
  181.                     in.close();  
  182.             } catch (Exception e2) {  
  183.   
  184.                 e2.printStackTrace();  
  185.             }  
  186.         }  
  187.   
  188.     }  
  189.   
  190.     public static void main(String[] args) throws Exception {  
  191.         // 传入要爬行的页面和保存HTML源码的文件地址  
  192.         new SearchCrawlerBreadth().downHTML("http://www.hao123.com/""src/html.txt");  
  193.         // 调用第二次的搜索  
  194.         new SearchCrawlerBreadth().search();  
  195.     }  
  196. }  

上面广度优先没啥问题,本人昨天凌晨3点多做的测试,15分钟左右的时间,这只小爬虫爬到了30W+的链接,能力还是蛮强大的么,顺便提一下,白天测试的时候会非常非常的慢,推荐各位测试君在晚上12点以后做测试。。。。。虽然不太人道。。。

下面是深度优先的代码,测试的时候每次都能造成死循环。。。好吧,我承认我没有人品。。。其实基本方法和广度优先没啥区别,我每个页面爬出来的链接只拿第一个去爬下一个页面,总共爬多少层我懒的木有定义,就是想看看最多能爬到哪。。。然后每次都能悲剧的死循环了。。。我明明也设置了跳出的方法了啊,我有判断有效链接的方式,但是我的判断并不完善么,跳出方法我写到了catch中,只要有一个无效链接,就可以跳出来了么。。。今天凌晨全都是死循环。。。。无奈了。。。。下面请代码君上场~~~~~~~~~~


[java]  view plain copy
  1. /** 
  2.  * 完成深度优先搜索 
  3.  * 爬虫进行深度优先很有可能会出现死循环的情况 
  4.  */  
  5. package net.meteor.java;  
  6.   
  7. import java.io.BufferedReader;  
  8. import java.io.FileInputStream;  
  9. import java.io.FileOutputStream;  
  10. import java.io.FileWriter;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13. import java.io.InputStreamReader;  
  14. import java.net.HttpURLConnection;  
  15. import java.net.URL;  
  16. import java.util.HashSet;  
  17. import java.util.Iterator;  
  18. import java.util.regex.Matcher;  
  19. import java.util.regex.Pattern;  
  20.   
  21. /** 
  22.  * @author 魏诗尧 
  23.  * @version 1.8 
  24.  * @emali inwsy@hotmail.com 
  25.  */  
  26. public class SearchCrawlerDepth {  
  27.     // 声明一个静态集合,用来存放爬虫爬到的URL  
  28.     private static HashSet<String> set = new HashSet<String>();  
  29.   
  30.     // 将网页源码下载到本地  
  31.     private void downHTMLDepth(String urlstr, String htmltxt) {  
  32.         // 声明链接  
  33.         HttpURLConnection con = null;  
  34.         // 声明输入流  
  35.         InputStream in = null;  
  36.         // 声明输出流  
  37.         FileOutputStream out = null;  
  38.   
  39.         try {  
  40.             // 实例化url  
  41.             URL url = new URL(urlstr);  
  42.             // 打开链接  
  43.             con = (HttpURLConnection) url.openConnection();  
  44.   
  45.             con.connect();  
  46.             // 打开输入流  
  47.             in = con.getInputStream();  
  48.             // 打开输出流创建接收文件  
  49.             out = new FileOutputStream(htmltxt);  
  50.   
  51.             byte[] b = new byte[1024];  
  52.   
  53.             int len = 0;  
  54.             // 将文件写入接收文件  
  55.             while ((len = in.read(b, 01024)) != -1) {  
  56.                 out.write(b, 0, len);  
  57.             }  
  58.   
  59.             new SearchCrawlerDepth().readTxtDepth("src/hrefdepth.txt");  
  60.         } catch (Exception e) {  
  61.             System.out.println("未知主机!!,爬行结束!!");  
  62.         } finally {  
  63.             try {  
  64.                 // 关闭流  
  65.                 if (out != null)  
  66.                     out.close();  
  67.                 if (in != null)  
  68.                     in.close();  
  69.   
  70.             } catch (Exception e) {  
  71.   
  72.                 e.printStackTrace();  
  73.             }  
  74.         }  
  75.     }  
  76.   
  77.     // 页面解析  
  78.     private void readTxtDepth(String hreftxt) {  
  79.         // 声明输入流  
  80.         InputStream in = null;  
  81.   
  82.         BufferedReader br = null;  
  83.   
  84.         try {  
  85.             // 实例化IO流,允许文件追加写  
  86.   
  87.             in = new FileInputStream("src/htmldepth1.txt");  
  88.   
  89.             br = new BufferedReader(new InputStreamReader(in));  
  90.             // 开始解析html  
  91.             A: while (br.readLine() != null) {  
  92.   
  93.                 String line = br.readLine();  
  94.                 // 创建正则表达式  
  95.                 Pattern pattern = Pattern.compile(  
  96.                         "<a\\s+href\\s*=\\s*\"?(.*?)[\"|>]",  
  97.                         Pattern.CASE_INSENSITIVE);  
  98.                 // 创建匹配器  
  99.                 Matcher matcher = pattern.matcher(line);  
  100.                 // 开始与正则表达式进行匹配  
  101.                 while (matcher.find()) {  
  102.                     String str = matcher.group(1);  
  103.                     // 跳过链到本页面内链接和无效链接  
  104.                     if (str.length() < 1) {  
  105.                         continue;  
  106.                     }  
  107.   
  108.                     if (str.charAt(0) == '#') {  
  109.                         continue;  
  110.                     }  
  111.                       
  112.                     if (str.startsWith("/")) {  
  113.                         continue;  
  114.                     }  
  115.   
  116.                     if (str.indexOf("mailto:") != -1) {  
  117.                         continue;  
  118.                     }  
  119.                     if (str.toLowerCase().indexOf("javascript") != -1) {  
  120.                         continue;  
  121.                     }  
  122.   
  123.                     if (str.startsWith("'")) {  
  124.                         continue;  
  125.                     }  
  126.                     // 将有效链接打印到屏幕  
  127.                     System.out.println(str);  
  128.                     // 将第一个有效链接写入到hashset  
  129.                      while (str != null) {  
  130.                         set.add(str);  
  131.                         new SearchCrawlerDepth().downHTMLDepth(str, "src/htmldepth1.txt");  
  132.                         break A;  
  133.                     }   
  134.                 }  
  135.             }  
  136.         } catch (Exception e) {  
  137.             System.out.println("无效链接!!本次爬行结束!!");  
  138.             new SearchCrawlerDepth().searchDepth();  
  139.         } finally {  
  140.             // 关闭IO流  
  141.             try {  
  142.   
  143.                 if (br != null)  
  144.                     br.close();  
  145.                 if (in != null)  
  146.                     in.close();  
  147.             } catch (Exception e) {  
  148.   
  149.                 e.printStackTrace();  
  150.             }  
  151.         }  
  152.     }  
  153.   
  154.     public void searchDepth() {  
  155.   
  156.         FileWriter file = null;  
  157.   
  158.         try {  
  159.             // 声明文件路径,可以追加写  
  160.             file = new FileWriter("src/hrefdepth1.txt"true);  
  161.             // 用迭代器遍历得到链接  
  162.             Iterator<String> it = set.iterator();  
  163.             while (it.hasNext()) {  
  164.                 System.out.println(it);  
  165.                 file.write(it + "\r\n");  
  166.             }  
  167.   
  168.         } catch (IOException e) {  
  169.             System.out.println("无效链接,本次爬行结束!!");  
  170.             e.printStackTrace();  
  171.         } finally {  
  172.   
  173.             try {  
  174.                 if (file != null)  
  175.                     file.close();  
  176.             } catch (IOException e) {  
  177.                   
  178.                 e.printStackTrace();  
  179.             }  
  180.         }  
  181.     }  
  182.       
  183.     public static void main(String[] args) {  
  184.         new SearchCrawlerDepth().downHTMLDepth("http://www.hao123.com""src/htmldepth1.txt");  
  185.         new SearchCrawlerDepth().searchDepth();  
  186.     }  
  187. }  

上面这两篇代码本身是十分不完善的,时间原因,我基本只实现了最基本的原理,能改动增加的地方还有很多,主要是增加,很多地方都可增加代码来增强程序的健壮性。。。比如有效链接判断的地方,我们从href标签中取出来的内容除了我写的几条判断意外还有好多东西都没有处理掉,这个地方还是能增加很多东西的。。。
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值