免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
一個(gè)簡(jiǎn)單的java網(wǎng)絡(luò)爬蟲(spider)

一個(gè)簡(jiǎn)單的java網(wǎng)絡(luò)爬蟲,由于時(shí)間原因,沒有進(jìn)一步解釋.

需要的htmlparser.jar包到官方網(wǎng)上去下.

 

  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 = "中國(guó)";//搜索關(guān)鍵字
  27. Parser parser = new Parser();
  28. // List linklist = new ArrayList();
  29. String startsite = "";//搜索的其實(shí)站點(diǎn)
  30. SearchResultBean srb;//保存搜索結(jié)果
  31. List resultlist = new ArrayList();//搜索到關(guān)鍵字鏈接列表
  32. List searchedsite = new ArrayList();//已經(jīng)被搜索站點(diǎn)列表
  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();//查找列隊(duì)
  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標(biāo)簽
  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標(biāo)簽結(jié)點(diǎn)
  108. * @param node
  109. * @throws Exception
  110. */
  111.     public void parserNode(Node node) throws Exception{
  112.     if (node instanceof StringNode) {//判斷是否是文本結(jié)點(diǎn)
  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) {//判斷是否是標(biāo)簽庫(kù)結(jié)點(diǎn)
  121.     Tag atag = (Tag) node;
  122.     if (atag instanceof TitleTag) {//判斷是否是標(biāo)TITLE結(jié)點(diǎn)
  123.      srb.setTitle(atag.getText());
  124.     }
  125.     if (atag instanceof LinkTag) {//判斷是否是標(biāo)LINK結(jié)點(diǎn)
  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.      * 檢查鏈接是否需要加入列隊(duì)
  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. * 檢查該鏈接是否已經(jīng)被掃描
  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的主機(jī)
  183.    // System.out.println("主機(jī)="+host);
  184.    // 獲取主機(jī)不允許搜索的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文件,創(chuàng)建不允許訪問的路徑列表。
  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.      // 緩存此主機(jī)不允許訪問的路徑。
  213.      disallowListCache.put(host, disallowList);
  214.     } catch (Exception e) {
  215.      return true; // web站點(diǎn)根目錄下沒有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();//啟動(dòng)線程
  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. }
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
使用 HttpClient 和 HtmlParser 實(shí)現(xiàn)簡(jiǎn)易爬蟲
抓取一個(gè)網(wǎng)站特定的全部圖片(JAVA)
htmlParser使用教程
定時(shí)抓取特定網(wǎng)站內(nèi)容
Java發(fā)送Http請(qǐng)求,解析html返回
java web 處理大量用戶并發(fā)提交的簡(jiǎn)單思路:隊(duì)列加定時(shí)提交
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服