Java Crawler Project Combat (i)

Source: Internet
Author: User

Objective: to crawl the least granular regional dimension information of China through web crawler, including the provinces (province), city, County (county), town, Village Committee (village) Main website Link: http://www.stats.go v.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2015/index.html main jar Package: Http://jsoup.org/packages/jsoup-1.8.1.jar

In the previous section, we said that the Java crawler uses Jsoup to get Web page text from the web, that is, we can have three ways to get the html, one is based on the URL link, but from the local path, and the third is to parse the string into an HTML document

In this case, we use the first two combinations:

See if there is a local web page, if it does not exist, get it by URL and save it locally (next time you don't need to reload from the Network)

We first build a class called the HTML class, the content is as Follows:

 packageProduct;Importjava.io.BufferedInputStream;Importjava.io.BufferedOutputStream;Importjava.io.File;Importjava.io.FileOutputStream;Importjava.io.IOException;Importjava.io.InputStream;Importjava.net.URL;Importjava.util.ArrayList;Importjava.util.Arrays;Importorg.jsoup.*;Importorg.jsoup.nodes.*;Importorg.jsoup.select.*; public classHtml {//get Web page text from the web based on a URL     publicdocument Gethtmltextbyurl (String Url) {document Doc=NULL; Try {            //doc = jsoup.connect (url). timeout (5000000). get ();            inti = (int) (math.random () *1000); //do a random delay to prevent site blocking
 while(i!=0)
{i
--; }
Doc
= Jsoup.connect (url). Data ("query", "Java")
. useragent (
"Mozilla"). Cookies ("auth", "token")
. Timeout (
300000). Post ();
}
Catch(ioexception E)
{e.printstacktrace ();
Try {
Doc
= Jsoup.connect (url). Timeout (5000000). Get ();
}
Catch(ioexception E1)
{
//TODO auto-generated Catch block E1.printstacktrace ();} }

returndoc;
}

//get Web page text based on local path, get and save from the network if it doesn't exist

publicDocument gethtmltextbypath (String name,string Url)
{
String Path
= "d:/html/" +name+ ". Html";
Document Doc
=NULL ;
File input
=NewFile (path);
String Urlcat
=url;
Try {
Doc
= Jsoup.parse (input, "GBK"));
if(!Doc.children (). isEmpty ())
{
Doc
=NULL; System.out.println ("already exists."); }
}
Catch(ioexception E)
{
System.out.println (
"file not found, getting from the network ...");
Doc
= this. Gethtmltextbyurl (url);
//and save to local
this. save_html (url, name); } returndoc;} Here is the function to save the page
//Save the page locally (via url, and save Name)     public  voidsave_html (String url,string Name) {Try{name= name+ ". html"; //System.out.print (name);File dest =NewFile ("d:/html/" +name);//D:\Html//receive byte input streamInputStream is; //byte output streamFileOutputStream fos =NewFileOutputStream (dest); URL Temp=NewURL (url); is=Temp.openstream (); //buffer for byte input streamBufferedinputstream bis =NewBufferedinputstream (is); //buffer the byte output streamBufferedoutputstream BOS =NewBufferedoutputstream (fos); intlength; byte[] bytes =New byte[1024*20];  while(length = Bis.read (bytes, 0, bytes.length))! =-1) {fos.write (bytes,0, length);                     } bos.close ();                     Fos.close ();                     Bis.close ();                 Is.close (); } Catch(ioexception E) {e.printstacktrace (); }             }



This way, through the HTML class, call the Gethtmltextbypath function, Pass in our link and the name you want to save, then you can extract the information from this page text

and download the entire page to our Local.

See our website is like This:

Using Google browse right-click to check the elements, we look at the yellow marked Parts:

We found that the text information and hyperlink information in the TD under the TR under the a tag, using our jsoup can be directly obtained this information, see the Details:

// get a list of elements within an element based on element properties     public Elements getelebyclass (Document doc,string className)    {        Elements Elementsnull;    
= Doc.select (className); Here we get to the HTML text doc, and the tool class name, note <tr class= "provincetr" >
return elements; All of the TR collections are returned Here.
}

When we call, we directly pass in the HTML text we get, and "tr.provincertr" as parameters, in order to parse the information inside the TR set,

That is TD two a tag href and text content: For example href= "12.html" Beijing

The code is as Follows:

//get information about provinces, cities, counties, etc.     publicArrayList getprovince (string name,string url, string Type) {ArrayList result=NewArrayList (); //"tr.provincetr"String ClassType = "tr." +type+ "tr"; //get Web pages from the Web//Document doc = This.gethtmltextbyurl (url); //get web pages from the local, if not, get from the networkDocument doc2 = this. Gethtmltextbypath (name,url);         System.out.println (name); if(doc2!=NULL) {Elements es= this. Getelebyclass (doc2,classtype); The collection of TR for(element E:es)//loop each element sequentially, i.e. a TR {if(e!=NULL){             for(element ec:e.children ())///a TR child element TD,TD contains a tag {string[] PRV=NewString[4]; Identity information: the original URL (current url) name (beijing) now the URL (that is, the URL of Beijing) type (prv) provinceif(ec.children (). First ()! =NULL)                {                //the original URLprv[0]=url; is the parameter URL//Identity nameSystem.out.println (ec.children (). first (). owntext ()); prv[1]=ec.children (). First (). owntext (); A label text such as: Beijing//Identity URL Address//System.out.println (ec.children (). first (). attr ("href")); //http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2015/index.htmlString ownurl=ec.children (). First (). attr ("abs:href"); The URL of Beijing//because If you get the word locally, it becomes the local url, so keep the URL from the network for the first time ,ensure that the URL is not empty                if(ownurl.length () <10) {CONNECTORCL C=NewCONNECTORCL (); Ownurl= C.selectone (prv[1]);//fetch from the database, this is another call to the database function, based on the name of the URL} prv[2]=ownurl; Such as: beijing's own URL System.out.println (prv[2]); //levelprv[3]=Type;//it's just a kind of transmission, there will be city, county, etc.//add all identities to the listResult.add (prv);} }}        }        }        returnresult; Back to all provinces information collection, storage database, field type: baseurl name Ownurl levelname (type) updatetime}

Java Crawler Project Combat (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.