Jsoup obtains data from all regions (cities, counties, towns, and villages) and jsoup
Recently, I am working on some things. I need a region data from all over the country, from the province, city, county, town, and township. A variety of DU Niang, a variety of Google, did not find a complete data. In the end, I tried to find a relatively complete piece of data, but the data here is only accurate to the town level, and there is no data at the village level (I later learned why through the analysis data source, haha) some of the data provided by the bloggers are redundant. For those with obsessive-compulsive disorder and the pursuit of perfection, I thought that I had to crawl this part of data by myself.
The content in the above blog is rich, and the bloggers Use php to implement it. As the top programming language ranking in 2015, we cannot be weak, next, let's take a look at how java crawls the data we want from the web page...
Step 1. Preparation (Data Source + tool ):
Data Source (the most authoritative official data up to now): http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2013/
Data crawling tool: http://jsoup.org/
Second
Step, Data source analysis:
First, I will not explain how to use the jsoup tool here. If you are interested, you can check it by yourself.
For Development, you should learn more about the use of some software tools. You can only know where to start when you encounter them during normal development. We encourage you to pay more attention to some software tools around you for future use. Before doing this, I did not know how to use jsoup, but I know what jsoup can do. When I need it, I can check the materials and learn it myself.
The above data source was released in 2013 by the National Bureau of Statistics of the People's Republic of China. Its accuracy and authority are self-evident.
Next we will analyze the structure of the data source, starting with the Home Page:
By analyzing the source code of the home page, we can get the following three points:
Let's take a look at the general data page (the general data page includes the municipal, county, and town data display pages ):
The reason why we need to put the above three pages together is that through analysis, we can find that the data pages of these three levels are completely consistent, the only difference is that the class attributes of the tr data row in the html source data table are inconsistent, which correspond to citytr and countrytrhe towntr respectively. Others are consistent. In this way, we can use a general method to solve the data crawling of the three pages.
Finally, let's look at the data page at the village level:
In the data at the village level, the data format is inconsistent with that of the cities, counties, and towns mentioned above. The data displayed at this level is at the lowest level, so there is no a link, therefore, you cannot crawl data from cities, counties, towns, and towns. The class of the table row that shows the data is deleagetr. Apart from these two points, each row contains three columns of data, the first column is citycode, the second column is the Urban and Rural classification (the data format of cities, counties and towns does not exist), and the third column is the city name.
In addition to the above points, we can start coding.
Step 3: Coding implementation:
1 import java. io. bufferedWriter; 2 import java. io. file; 3 import java. io. fileWriter; 4 import java. io. IOException; 5 import java. util. hashMap; 6 import java. util. map; 7 8 import org. jsoup. jsoup; 9 import org. jsoup. nodes. document; 10 import org. jsoup. nodes. element; 11 import org. jsoup. select. elements; 12 13/** 14 * Data crawling across provinces, cities, towns, and villages in China * @ author liushaofeng 16 * @ date 12:19:39 17 * @ version 1.0.0 18 */19 public class JsoupTest 20 {21 private static Map <Integer, String> cssMap = new HashMap <Integer, String> (); 22 private static BufferedWriter bufferedWriter = null; 23 24 static 25 {26 cssMap. put (1, "provincetr"); // save 27 cssMap. put (2, "citytr"); // City 28 cssMap. put (3, "countytr"); // County 29 cssMap. put (4, "towntr"); // town 30 cssMap. put (5, "villagetr"); // village 31} 32 33 public static void main (String [] args) throws IOException 34 {35 int level = 1; 36 37 initFile (); 38 39 // obtain provincial information nationwide 40 Document connect = connect ("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2013/"); 41 Elements rowProvince = connect. select ("tr. "+ cssMap. get (level); 42 for (Element provinceElement: rowProvince) // traverse the Province cities of each row 43 {44 Elements select = provinceElement. select ("a"); 45 for (Element province: sele Ct) // each province (Sichuan province) 46 {47 parseNextLevel (province, level + 1); 48} 49} 50 51 closeStream (); 52} 53 54 private static void initFile () 55 {56 try 57 {58 bufferedWriter = new BufferedWriter (new FileWriter (new File ("d: \ CityInfo.txt "), true); 59} catch (IOException e) 60 {61 e. printStackTrace (); 62} 63} 64 65 private static void closeStream () 66 {67 if (bufferedWriter! = Null) 68 {69 try 70 {71 bufferedWriter. close (); 72} catch (IOException e) 73 {74 e. printStackTrace (); 75} 76 bufferedWriter = null; 77} 78} 79 80 private static void parseNextLevel (Element parentElement, int level) throws IOException 81 {82 try 83 {84 Thread. sleep (500); // sleep. Otherwise, various error codes may occur: 85} catch (InterruptedException e) 86 {87 e. printStackTrace (); 88} 89 90 Document doc = connect (ParentElement. attr ("abs: href"); 91 if (doc! = Null) 92 {93 Elements newsHeadlines = doc. select ("tr. "+ cssMap. get (level); // 94 // get a row of data in the table 95 for (Element element: newsHeadlines) 96 {97 printInfo (element, level + 1 ); 98 Elements select = element. select ("a"); // when calling recursively, it is used to determine whether the data is at the village level. The data at the village level does not have the tag 99 if (select. size ()! = 0) 100 {101 parseNextLevel (select. last (), level + 1 ); 102} 103} 104} 105 106 107/** 108 * write a row of data to the data file to go to 109 * @ param element to crawl the data element 110 * @ param level city level 111 */112 private static void printInfo (Element element, int level) 113 {114 try115 {116 bufferedWriter. write (element. select ("td "). last (). text () + "{" + level + "} [" 117 + element. select ("td "). first (). text () + "]"); 118 bufferedWriter. newLine (); 119 BufferedWriter. flush (); 120} catch (IOException e) 121 {122 e. printStackTrace (); 123} 124} 125 126 private static Document connect (String url) 127 {128 if (url = null | url. isEmpty () 129 {130 throw new IllegalArgumentException ("The input url ('" + url + "') is invalid! "); 131} 132 trygroups {134 return Jsoup. connect (url ). timeout (100*1000 ). get (); 135} catch (IOException e) 136 {137 e. printStackTrace (); 138 return null; 139} 140} 141}
The data crawling process is a long process. You just need to wait for a long time ....
The final format of the obtained data is as follows ("{}" indicates the city level, and "[]" indicates the city code ):
Municipal District {3} [110100000000] Dongcheng District {4} [110101000000] donghuamen sub-district office {5} [110101001000] duofu Lane community neighborhood committee {6} [110101001001] yinzha community neighborhood committee {6} [110101001002] dongchang community residents' committee {6} [110101001005] zhide community residents' committee {6} [110101001006] nanchi subcommunity residents' committee {6} [110101001007] huangtugang community residents' committee {6} [110101001008] dengshikou community neighborhood committee {6} [110101001009] Zhengyi road community neighborhood committee {6} [110101001010] Gan Yu community neighborhood committee {6} [110101001011] Taiji factory community neighborhood committee {6} [110101001013] Yi 9 community neighborhood committee {6} [110101001014] Wangfujing community neighborhood committee {6} [110101001015] jingshan sub-district office {5} [110101002000] longfu temple community neighborhood committee {6} [110101002001] auspicious community neighborhood committee {6} [110101002002] huanghuamen community residents' committee {6} [110101002003] zhonggu community residents' committee {6} [110101002004] Wei Jia community residents' committee {6} [110101002005] Wang zhima community residents' committee {6} [110101002006] jingshan East Street community neighborhood committee {6} [110101002008] huangchenggen North Street community neighborhood committee {6} [110101002009] jiaodaokou sub-district office {5} [110101003000] Jiaodong community neighborhood committee {6} [110101003001] fuxiang community neighborhood committee {6} [110101003002] Daxing community neighborhood committee {6} [110101003003] fu Xue community neighborhood committee {6} [110101003005] guluyuan community neighborhood committee {6} [110101003007] juer community neighborhood committee {6} [110101003008] nanluoguxiang community neighborhood committee {6} [110101003009] andingmen sub-district office {5} [110101004000] Jiaobei toutiao community neighborhood committee {6} [110101004001] North luoguxiang community neighborhood committee {6} [110101004002] guozijian community residents' committee {6} [110101004003] ......
After obtaining the above data, you can implement what you want. The above code can be run directly. After crawling from the data source, you can directly convert it into the desired format.
If you think this blog is helpful to you,Please remember to click "recommendation" in the lower right corner.What...
Reprinted please indicate the source: http://www.cnblogs.com/liushaofeng89/p/4873086.html