一个简单的java网络爬虫(spider)

来源:互联网 发布:springmvc4 json配置 编辑:程序博客网 时间:2024/05/14 07:57

一个简单的java网络爬虫,由于时间原因,没有进一步解释.

需要的htmlparser.jar包到官方网上去下.

 

  1. ---------------------------------------------Spider.java-----------------------------------------------------------------
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.net.URL;
  5. import java.net.URLConnection;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.Iterator;
  9. import java.util.List;
  10. import org.htmlparser.RemarkNode;
  11. import org.htmlparser.StringNode;
  12. import org.htmlparser.Node;
  13. import org.htmlparser.tags.*;
  14. import org.htmlparser.Parser;
  15. import org.htmlparser.filters.StringFilter;
  16. import org.htmlparser.util.NodeIterator;
  17. import org.htmlparser.util.NodeList;
  18. import org.htmlparser.util.ParserException;
  19. import java.util.Queue;
  20. import java.util.LinkedList;
  21. public class Spider implements Runnable {
  22. boolean search_key_words = false;
  23. int count = 0;
  24. int limitsite = 10;
  25. int countsite = 1;
  26. String keyword = "中国";//搜索关键字
  27. Parser parser = new Parser();
  28. // List linklist = new ArrayList();
  29. String startsite = "";//搜索的其实站点
  30. SearchResultBean srb;//保存搜索结果
  31. List resultlist = new ArrayList();//搜索到关键字链接列表
  32. List searchedsite = new ArrayList();//已经被搜索站点列表
  33. Queue linklist = new LinkedList();//需解析的链接列表
  34. HashMap<String, ArrayList<String>> disallowListCache = new HashMap<String, ArrayList<String>>();
  35. public Spider(String keyword, String startsite) {
  36.    this.keyword = keyword;
  37.    this.startsite = startsite;
  38.    linklist.add(startsite);
  39.    srb = new SearchResultBean();
  40. }
  41. public void run() {
  42.    // TODO Auto-generated method stub
  43.    search(linklist);
  44. }
  45. public void search(Queue queue) {
  46.    String url = "";
  47.      while(!queue.isEmpty()){
  48.     url = queue.peek().toString();//查找列队
  49.     try {
  50.      if (!isSearched(searchedsite, url)) {
  51.       if (isRobotAllowed(new URL(url)))//检查该链接是否被允许搜索
  52.        processHtml(url);
  53.       else
  54.        System.out.println("this page is disallowed to search");
  55.      }
  56.     } catch (Exception ex) {
  57.     }
  58.     queue.remove();
  59.   
  60.      }
  61.     
  62. }
  63. /**
  64. * 解析HTML
  65. * @param url 
  66. * @throws ParserException
  67. * @throws Exception
  68. */
  69. public void processHtml(String url) throws ParserException, Exception {
  70.    searchedsite.add(url);
  71.    count = 0;
  72.    System.out.println("searching ... :" + url);
  73.    parser.setURL(url);
  74.    parser.setEncoding("GBK");
  75.    URLConnection uc = parser.getConnection();
  76.    uc.connect();
  77.    //uc.getLastModified();
  78.    NodeIterator nit = parser.elements();
  79.   
  80.    while (nit.hasMoreNodes()) {
  81.     Node node = nit.nextNode();
  82.     parserNode(node);
  83.    }
  84.    srb.setKeywords(keyword);
  85.    srb.setUrl(url);
  86.    srb.setCount_key_words(count);
  87.    resultlist.add(srb);
  88.    System.out.println("count keywords is :" + count);
  89.    System.out.println("----------------------------------------------");
  90. }
  91. /**
  92. * 处理HTML标签
  93. * @param tag
  94. * @throws Exception
  95. */
  96. public void dealTag(Tag tag) throws Exception {
  97.    NodeList list = tag.getChildren();
  98.    if (list != null) {
  99.     NodeIterator it = list.elements();
  100.     while (it.hasMoreNodes()) {
  101.      Node node = it.nextNode();
  102.      parserNode(node);
  103.     }
  104.    }
  105. }
  106. /**
  107. * 处理HTML标签结点
  108. * @param node
  109. * @throws Exception
  110. */
  111.     public void parserNode(Node node) throws Exception{
  112.     if (node instanceof StringNode) {//判断是否是文本结点
  113.     StringNode sNode = (StringNode) node;
  114.     StringFilter sf = new StringFilter(keyword,false);
  115.     search_key_words = sf.accept(sNode);
  116.     if (search_key_words) {
  117.      count++;
  118.     }
  119.     // System.out.println("text is :"+sNode.getText().trim());
  120.    } else if (node instanceof Tag) {//判断是否是标签库结点
  121.     Tag atag = (Tag) node;
  122.     if (atag instanceof TitleTag) {//判断是否是标TITLE结点
  123.      srb.setTitle(atag.getText());
  124.     }
  125.     if (atag instanceof LinkTag) {//判断是否是标LINK结点
  126.      LinkTag linkatag = (LinkTag) atag;
  127.      checkLink(linkatag.getLink(), linklist);
  128.      // System.out.println("-----------------this is link --------------");
  129.     }
  130.     dealTag(atag);
  131.    } else if (node instanceof RemarkNode) {//判断是否是注释
  132.     // System.out.println("this is remark");
  133.    }
  134.     }
  135.     /*
  136.      * 检查链接是否需要加入列队
  137.      */
  138. public void checkLink(String link, Queue queue) {
  139.    if (link != null && !link.equals("") && link.indexOf("#") == -1) {
  140.     if (!link.startsWith("http://") && !link.startsWith("ftp://")
  141.       && !link.startsWith("www.")) {
  142.      link = "file:///" + link;
  143.     } else if (link.startsWith("www.")) {
  144.      link = "http://" + link;
  145.     }
  146.     if (queue.isEmpty())
  147.      queue.add(link);
  148.     else {
  149.      String link_end_=link.endsWith("/")?link.substring(0,link.lastIndexOf("/")):(link+"/");
  150.      if (!queue.contains(link)&&!queue .contains(link_end_)) {
  151.       queue.add(link);
  152.      }
  153.     }
  154.    }
  155. }
  156. /**
  157. * 检查该链接是否已经被扫描
  158. * @param list
  159. * @param url
  160. * @return
  161. */
  162. public boolean isSearched(List list, String url) {
  163.    String url_end_ = "";
  164.    if (url.endsWith("/")) {
  165.     url_end_ = url.substring(0, url.lastIndexOf("/"));
  166.    } else {
  167.     url_end_ = url + "/";
  168.    }
  169.    if (list.size() > 0) {
  170.     if (list.indexOf(url) != -1 || list.indexOf(url_end_) != -1) {
  171.      return true;
  172.     }
  173.    }
  174.    return false;
  175. }
  176. /**
  177. * 检查URL是否被允许搜索
  178. * @param urlToCheck
  179. * @return
  180. */
  181. private boolean isRobotAllowed(URL urlToCheck) {
  182.    String host = urlToCheck.getHost().toLowerCase();// 获取给出RUL的主机
  183.    // System.out.println("主机="+host);
  184.    // 获取主机不允许搜索的URL缓存
  185.    ArrayList<String> disallowList = disallowListCache.get(host);
  186.    // 如果还没有缓存,下载并缓存。
  187.    if (disallowList == null) {
  188.     disallowList = new ArrayList<String>();
  189.     try {
  190.      URL robotsFileUrl = new URL("http://" + host + "/robots.txt");
  191.      BufferedReader reader = new BufferedReader(
  192.        new InputStreamReader(robotsFileUrl.openStream()));
  193.      // 读robot文件,创建不允许访问的路径列表。
  194.      String line;
  195.      while ((line = reader.readLine()) != null) {
  196.       if (line.indexOf("Disallow:") == 0) {// 是否包含"Disallow:"
  197.        String disallowPath = line.substring("Disallow:"
  198.          .length());// 获取不允许访问路径
  199.        // 检查是否有注释。
  200.        int commentIndex = disallowPath.indexOf("#");
  201.        if (commentIndex != -1) {
  202.         disallowPath = disallowPath.substring(0,
  203.           commentIndex);// 去掉注释
  204.        }
  205.        disallowPath = disallowPath.trim();
  206.        disallowList.add(disallowPath);
  207.       }
  208.      }
  209.      for (Iterator it = disallowList.iterator(); it.hasNext();) {
  210.       System.out.println("Disallow is :" + it.next());
  211.      }
  212.      // 缓存此主机不允许访问的路径。
  213.      disallowListCache.put(host, disallowList);
  214.     } catch (Exception e) {
  215.      return true// web站点根目录下没有robots.txt文件,返回真
  216.     }
  217.    }
  218.    String file = urlToCheck.getFile();
  219.    // System.out.println("文件getFile()="+file);
  220.    for (int i = 0; i < disallowList.size(); i++) {
  221.     String disallow = disallowList.get(i);
  222.     if (file.startsWith(disallow)) {
  223.      return false;
  224.     }
  225.    }
  226.    return true;
  227. }
  228. public static void main(String[] args) {
  229.    Spider ph = new Spider("英超""http://www.microsoft.com");
  230.    try {
  231.     // ph.processHtml();
  232.     Thread search = new Thread(ph);
  233.     search.start();//启动线程
  234.    } catch (Exception ex) {
  235.    }
  236. }
  237. }
  238. --------------------------------------SearchResultBean.java---------------------------------------------------------
  239. public class SearchResultBean {
  240.    String url = "";
  241.    String title = "";
  242.    String keywords = "";
  243.    int count_key_words = 0;
  244. public int getCount_key_words() {
  245. return count_key_words;
  246. }
  247. public void setCount_key_words(int count_key_words) {
  248. this.count_key_words = count_key_words;
  249. }
  250. public String getKeywords() {
  251. return keywords;
  252. }
  253. public void setKeywords(String keywords) {
  254. this.keywords = keywords;
  255. }
  256. public String getTitle() {
  257. return title;
  258. }
  259. public void setTitle(String title) {
  260. this.title = title;
  261. }
  262. public String getUrl() {
  263. return url;
  264. }
  265. public void setUrl(String url) {
  266. this.url = url;
  267. }
  268. }
原创粉丝点击