Recent Research crawler Crawl site Links:
1. Need to get all the hyperlinks
2. Exclude crawled links, go to heavy
3. Research on the breadth and depth of crawler (PS: No research is exhaustive)
Here is the implementation code:
Import Java.io.bufferedreader;import java.io.inputstream;import java.io.inputstreamreader;import Java.net.URL; Import Java.net.urlconnection;import java.util.arraylist;import Java.util.hashmap;import Java.util.HashSet;import Java.util.list;import Java.util.map;import Java.util.set;import Java.util.regex.matcher;import Java.util.regex.pattern;import Javax.swing.plaf.synth.synthspinnerui;public class Study {private static list< String> waitforurl=new arraylist<> ()///store crawled URLs, waiting to crawl private static set<string> goforurl=new hashset& Lt;> ()///store crawled URL private static map<string,integer> allurldepth=new hashmap<> ();//crawl depth of all URLs to judge the PRI vate static int maxdepth=2; public static void Main (string[] args) {String urlstr= "..."); Study.gourl (URLSTR, 1); } public static void Gourl (String urlstr,int depath) {if (! ( Goforurl.contains (URLSTR) | | depath>maxdepth)) {Goforurl.add (URLSTR); try { URL url=new url (urlstr); URLConnection urlconn=url.openconnection ();//Establish a URL link inputstream is=urlconn.getinputstream ();//Get the page content through a link for byte stream InputStreamReader isr=new InputStreamReader (IS, "utf-8");//convert bytes to character stream BufferedReader Br=n EW BufferedReader (ISR);//Read byte stream stringbuffer sb=new stringbuffer ();//instantiate StringBuffer to store read data String Line=null; while ((Line=br.readline ())!=null) {sb.append (line); System.out.println (line); Pattern p = pattern.compile ("<a .*href=.+</a>"); Matcher M=p.matcher (line); while (M.find ()) {String href=m.group (); Href=href.substring (Href.indexof ("href=")); if (Href.charat (5) = = ' \ ' ' | | Href.charat (5) = = ' \ ') {href=href.substring (6); }else{ Href=href.substring (5); } try {href=href.substring (0,href.indexof ("\" ")); }catch (Exception e) {href=href.substring (0,href.indexof ("\")); } waitforurl.add (HREF); Allurldepth.put (href, depath+1); }} is.close ();//Close output stream isr.close ();//close byte stream read Br.close (); System.out.println (URLSTR); SYSTEM.OUT.PRINTLN ("Total number of Links:" +waitforurl.size () + ", Number of crawled Links:" +goforurl.size ()); }catch (Exception e) {e.printstacktrace (); }//Continue crawling other links with a recursive method String nexturl=waitforurl.get (0); Waitforurl.remove (0); Gourl (Nexturl,allurldepth.get (Nexturl)); }//else is if a duplicate link is present if you continue to crawl else {String NEXTURL=WAITFORURL.GET (0); Waitforurl.remove (0); Gourl (Nexturl,allurldepth.get (Nexturl)); } }}
The crawler of Java