在涉及地址服務時,常常須要用到地址信息的獲取,而行政區劃可能不按期的發生變化,因此咱們須要獲取最新的行政區劃信息。因行政區劃數據量較大,Java中可使用Jsoup進行數據的獲取、處理。html
你們常常用到的行政區劃數據,可從中華人民共和國民政部網站上獲取,響應請求連接以下所示:web
http://www.mca.gov.cn/article/sj/xzqh/2019/app
界面以下圖所示:dom
截至當前對應的行政區劃數據請求連接爲:http://www.mca.gov.cn/article/sj/xzqh/2019/201901-06/201904301706.html ,對應的頁面顯示以下所示:網站
經過觀察中華人民共和國縣以上行政區劃代碼的列表中能夠看出行政區劃代碼基本規則:url
頁面部分源碼以下所示:spa
可知:行政區劃代碼數據存儲在 table 中,表格的第二列存放「行政區劃代碼」,表格的第三列存放「單位名稱」;3d
爬取思路以下:code
一、獲取響應結果的 dom 樹;orm
二、獲取全部的行標籤;
三、便利全部的列標籤,獲取擁有三個以上子列的行信息,並取第 2 列和第 3 列;
四、依據行政區劃代碼基本規則,進行數據的標示;
五、輸出得到的行政區劃數據,此處輸出爲 SQL 插入語句。
源代碼以下所示:
@Test public void getRegionSql () throws Exception { String url = "http://www.mca.gov.cn/article/sj/xzqh/2019/201901-06/201904301706.html"; int count = 0; Document doc = Jsoup.connect(url) .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36") .header("Accept", "text/html,application/xhtml+xml,application/xmlq=0.9,image/webp,image/apng,*/*q=0.8,application/signed-exchangev=b3") .maxBodySize(0) .timeout(100000) .get(); Elements trs = doc.select("tr"); for (Element tr : trs ) { Elements tds = tr.select("td"); if (tds.size() > 3) { String regionCode = tds.get(1).text(); String regionArea = tds.get(2).text(); String parentCode = ""; if (validCode(regionCode)) { int leveType = 2; parentCode = regionCode.substring(0,2) + "0000"; if (!regionCode.endsWith("00")) { leveType = 3; parentCode = regionCode.substring(0,4) + "00"; } if (regionCode.endsWith("0000")) { leveType = 1; parentCode = "000000"; } count++; String content = String.format("insert into region_code (code, name, level, parent_code, dtime, note, ctime)" + " values (%s, '%s', %s, %s, '201903', '系統生成', NOW());" + System.getProperty("line.separator"), regionCode, regionArea, leveType, parentCode); System.out.println(content); } } } System.out.println("總數量爲:" + count); }