[Java] java web蜘蛛 网络爬虫 →→→→→进入此内容的聊天室

来自 , 2021-01-11, 写在 Java, 查看 104 次.
URL http://www.code666.cn/view/3a066bda
  1. import java.util.*;
  2. import java.net.*;
  3. import java.io.*;
  4. import java.util.regex.*;
  5.  
  6. // 搜索Web爬行者,从命令行输入搜索条件(起始的URL、处理url的最大数、要搜索的字符串)
  7. public class SearchCrawler implements Runnable {
  8.  
  9.         /*
  10.          * disallowListCache缓存robot不允许搜索的URL。 Robot协议在Web站点的根目录下设置一个robots.txt文件,
  11.          * 规定站点上的哪些页面是限制搜索的。 搜索程序应该在搜索过程中跳过这些区域,下面是robots.txt的一个例子: # robots.txt for
  12.          * [url]http://somehost.com/[/url] User-agent: * Disallow: /cgi-bin/
  13.          * Disallow: /registration # /Disallow robots on registration page Disallow:
  14.          * /login
  15.          */
  16.  
  17.         private HashMap<String, ArrayList<String>> disallowListCache = new HashMap<String, ArrayList<String>>();
  18.         ArrayList<String> errorList = new ArrayList<String>();// 错误信息
  19.         ArrayList<String> result = new ArrayList<String>(); // 搜索到的结果
  20.         String startUrl;// 开始搜索的起点
  21.         int maxUrl;// 最大处理的url数
  22.         String searchString;// 要搜索的字符串(英文)
  23.         boolean caseSensitive = false;// 是否区分大小写
  24.         boolean limitHost = false;// 是否在限制的主机内搜索
  25.  
  26.         public SearchCrawler(String startUrl, int maxUrl, String searchString) {
  27.                 this.startUrl = startUrl;
  28.                 this.maxUrl = maxUrl;
  29.                 this.searchString = searchString;
  30.         }
  31.  
  32.         public ArrayList<String> getResult() {
  33.                 return result;
  34.         }
  35.  
  36.         public void run() {// 启动搜索线程
  37.  
  38.                 crawl(startUrl, maxUrl, searchString, limitHost, caseSensitive);
  39.         }
  40.  
  41.         // 检测URL格式
  42.         private URL verifyUrl(String url) {
  43.                 // 只处理HTTP URLs.
  44.                 if (!url.toLowerCase().startsWith("http://"))
  45.                         return null;
  46.  
  47.                 URL verifiedUrl = null;
  48.                 try {
  49.                         verifiedUrl = new URL(url);
  50.                 } catch (Exception e) {
  51.                         return null;
  52.                 }
  53.  
  54.                 return verifiedUrl;
  55.         }
  56.  
  57.         // 检测robot是否允许访问给出的URL.
  58.         private boolean isRobotAllowed(URL urlToCheck) {
  59.                 String host = urlToCheck.getHost().toLowerCase();// 获取给出RUL的主机
  60.                 // System.out.println("主机="+host);
  61.  
  62.                 // 获取主机不允许搜索的URL缓存
  63.                 ArrayList<String> disallowList = disallowListCache.get(host);
  64.  
  65.                 // 如果还没有缓存,下载并缓存。
  66.                 if (disallowList == null) {
  67.                         disallowList = new ArrayList<String>();
  68.                         try {
  69.                                 URL robotsFileUrl = new URL("http://" + host + "/robots.txt");
  70.                                 BufferedReader reader = new BufferedReader(
  71.                                                 new InputStreamReader(robotsFileUrl.openStream()));
  72.  
  73.                                 // 读robot文件,创建不允许访问的路径列表。
  74.                                 String line;
  75.                                 while ((line = reader.readLine()) != null) {
  76.                                         if (line.indexOf("Disallow:") == 0) {// 是否包含"Disallow:"
  77.                                                 String disallowPath = line.substring("Disallow:"
  78.                                                                 .length());// 获取不允许访问路径
  79.  
  80.                                                 // 检查是否有注释。
  81.                                                 int commentIndex = disallowPath.indexOf("#");
  82.                                                 if (commentIndex != -1) {
  83.                                                         disallowPath = disallowPath.substring(0,
  84.                                                                         commentIndex);// 去掉注释
  85.                                                 }
  86.  
  87.                                                 disallowPath = disallowPath.trim();
  88.                                                 disallowList.add(disallowPath);
  89.                                         }
  90.                                 }
  91.  
  92.                                 // 缓存此主机不允许访问的路径。
  93.                                 disallowListCache.put(host, disallowList);
  94.                         } catch (Exception e) {
  95.                                 return true; // web站点根目录下没有robots.txt文件,返回真
  96.                         }
  97.                 }
  98.  
  99.                 String file = urlToCheck.getFile();
  100.                 // System.out.println("文件getFile()="+file);
  101.                 for (int i = 0; i < disallowList.size(); i++) {
  102.                         String disallow = disallowList.get(i);
  103.                         if (file.startsWith(disallow)) {
  104.                                 return false;
  105.                         }
  106.                 }
  107.  
  108.                 return true;
  109.         }
  110.  
  111.         private String downloadPage(URL pageUrl) {
  112.                 try {
  113.                         // Open connection to URL for reading.
  114.                         BufferedReader reader = new BufferedReader(new InputStreamReader(
  115.                                         pageUrl.openStream()));
  116.  
  117.                         // Read page into buffer.
  118.                         String line;
  119.                         StringBuffer pageBuffer = new StringBuffer();
  120.                         while ((line = reader.readLine()) != null) {
  121.                                 pageBuffer.append(line);
  122.                         }
  123.  
  124.                         return pageBuffer.toString();
  125.                 } catch (Exception e) {
  126.                 }
  127.  
  128.                 return null;
  129.         }
  130.  
  131.         // 从URL中去掉"www"
  132.         private String removeWwwFromUrl(String url) {
  133.                 int index = url.indexOf("://www.");
  134.                 if (index != -1) {
  135.                         return url.substring(0, index + 3) + url.substring(index + 7);
  136.                 }
  137.  
  138.                 return (url);
  139.         }
  140.  
  141.         // 解析页面并找出链接
  142.         private ArrayList<String> retrieveLinks(URL pageUrl, String pageContents,
  143.                         HashSet crawledList, boolean limitHost) {
  144.                 // 用正则表达式编译链接的匹配模式。
  145.                 Pattern p = Pattern.compile("<a\\s+href\\s*=\\s*\"?(.*?)[\"|>]",
  146.                                 Pattern.CASE_INSENSITIVE);
  147.                 Matcher m = p.matcher(pageContents);
  148.  
  149.                 ArrayList<String> linkList = new ArrayList<String>();
  150.                 while (m.find()) {
  151.                         String link = m.group(1).trim();
  152.  
  153.                         if (link.length() < 1) {
  154.                                 continue;
  155.                         }
  156.  
  157.                         // 跳过链到本页面内链接。
  158.                         if (link.charAt(0) == '#') {
  159.                                 continue;
  160.                         }
  161.  
  162.                         if (link.indexOf("mailto:") != -1) {
  163.                                 continue;
  164.                         }
  165.  
  166.                         if (link.toLowerCase().indexOf("javascript") != -1) {
  167.                                 continue;
  168.                         }
  169.  
  170.                         if (link.indexOf("://") == -1) {
  171.                                 if (link.charAt(0) == '/') {// 处理绝对地
  172.                                         link = "http://" + pageUrl.getHost() + ":"
  173.                                                         + pageUrl.getPort() + link;
  174.                                 } else {
  175.                                         String file = pageUrl.getFile();
  176.                                         if (file.indexOf('/') == -1) {// 处理相对地址
  177.                                                 link = "http://" + pageUrl.getHost() + ":"
  178.                                                                 + pageUrl.getPort() + "/" + link;
  179.                                         } else {
  180.                                                 String path = file.substring(0,
  181.                                                                 file.lastIndexOf('/') + 1);
  182.                                                 link = "http://" + pageUrl.getHost() + ":"
  183.                                                                 + pageUrl.getPort() + path + link;
  184.                                         }
  185.                                 }
  186.                         }
  187.  
  188.                         int index = link.indexOf('#');
  189.                         if (index != -1) {
  190.                                 link = link.substring(0, index);
  191.                         }
  192.  
  193.                         link = removeWwwFromUrl(link);
  194.  
  195.                         URL verifiedLink = verifyUrl(link);
  196.                         if (verifiedLink == null) {
  197.                                 continue;
  198.                         }
  199.  
  200.                         /* 如果限定主机,排除那些不合条件的URL */
  201.                         if (limitHost
  202.                                         && !pageUrl.getHost().toLowerCase()
  203.                                                         .equals(verifiedLink.getHost().toLowerCase())) {
  204.                                 continue;
  205.                         }
  206.  
  207.                         // 跳过那些已经处理的链接.
  208.                         if (crawledList.contains(link)) {
  209.                                 continue;
  210.                         }
  211.  
  212.                         linkList.add(link);
  213.                 }
  214.  
  215.                 return (linkList);
  216.         }
  217.  
  218.         // 搜索下载Web页面的内容,判断在该页面内有没有指定的搜索字符串
  219.  
  220.         private boolean searchStringMatches(String pageContents,
  221.                         String searchString, boolean caseSensitive) {
  222.                 String searchContents = pageContents;
  223.                 if (!caseSensitive) {// 如果不区分大小写
  224.                         searchContents = pageContents.toLowerCase();
  225.                 }
  226.  
  227.                 Pattern p = Pattern.compile("[\\s]+");
  228.                 String[] terms = p.split(searchString);
  229.                 for (int i = 0; i < terms.length; i++) {
  230.                         if (caseSensitive) {
  231.                                 if (searchContents.indexOf(terms[i]) == -1) {
  232.                                         return false;
  233.                                 }
  234.                         } else {
  235.                                 if (searchContents.indexOf(terms[i].toLowerCase()) == -1) {
  236.                                         return false;
  237.                                 }
  238.                         }
  239.                 }
  240.  
  241.                 return true;
  242.         }
  243.  
  244.         // 执行实际的搜索操作
  245.         public ArrayList<String> crawl(String startUrl, int maxUrls,
  246.                         String searchString, boolean limithost, boolean caseSensitive) {
  247.  
  248.                 System.out.println("searchString=" + searchString);
  249.                 HashSet<String> crawledList = new HashSet<String>();
  250.                 LinkedHashSet<String> toCrawlList = new LinkedHashSet<String>();
  251.  
  252.                 if (maxUrls < 1) {
  253.                         errorList.add("Invalid Max URLs value.");
  254.                         System.out.println("Invalid Max URLs value.");
  255.                 }
  256.  
  257.                 if (searchString.length() < 1) {
  258.                         errorList.add("Missing Search String.");
  259.                         System.out.println("Missing search String");
  260.                 }
  261.  
  262.                 if (errorList.size() > 0) {
  263.                         System.out.println("err!!!");
  264.                         return errorList;
  265.                 }
  266.  
  267.                 // 从开始URL中移出www
  268.                 startUrl = removeWwwFromUrl(startUrl);
  269.  
  270.                 toCrawlList.add(startUrl);
  271.                 while (toCrawlList.size() > 0) {
  272.  
  273.                         if (maxUrls != -1) {
  274.                                 if (crawledList.size() == maxUrls) {
  275.                                         break;
  276.                                 }
  277.                         }
  278.  
  279.                         // Get URL at bottom of the list.
  280.                         String url = toCrawlList.iterator().next();
  281.  
  282.                         // Remove URL from the to crawl list.
  283.                         toCrawlList.remove(url);
  284.  
  285.                         // Convert string url to URL object.
  286.                         URL verifiedUrl = verifyUrl(url);
  287.  
  288.                         // Skip URL if robots are not allowed to access it.
  289.                         if (!isRobotAllowed(verifiedUrl)) {
  290.                                 continue;
  291.                         }
  292.  
  293.                         // 增加已处理的URL到crawledList
  294.                         crawledList.add(url);
  295.                         String pageContents = downloadPage(verifiedUrl);
  296.  
  297.                         if (pageContents != null && pageContents.length() > 0) {
  298.                                 // 从页面中获取有效的链接
  299.                                 ArrayList<String> links = retrieveLinks(verifiedUrl,
  300.                                                 pageContents, crawledList, limitHost);
  301.  
  302.                                 toCrawlList.addAll(links);
  303.  
  304.                                 if (searchStringMatches(pageContents, searchString,
  305.                                                 caseSensitive)) {
  306.                                         result.add(url);
  307.                                         System.out.println(url);
  308.                                 }
  309.                         }
  310.  
  311.                 }
  312.                 return result;
  313.         }
  314.  
  315.         // 主函数
  316.         public static void main(String[] args) {
  317.                 if (args.length != 3) {
  318.                         System.out
  319.                                         .println("Usage:java SearchCrawler startUrl maxUrl searchString");
  320.                         return;
  321.                 }
  322.                 int max = Integer.parseInt(args[1]);
  323.                 SearchCrawler crawler = new SearchCrawler(args[0], max, args[2]);
  324.                 Thread search = new Thread(crawler);
  325.                 System.out.println("Start searching...");
  326.                 System.out.println("result:");
  327.                 search.start();
  328.  
  329.         }
  330. }

回复 "java web蜘蛛 网络爬虫"

这儿你可以回复上面这条便签

captcha