主網站鏈接:
http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2015/index.html
主要jar包:
http://jsoup.org/packages/jsoup-1.8.1.jar
之前一節我們說過java爬蟲從網絡上利用jsoup獲取網頁文本,也就是說我們可以有三種方法獲取html,一是根據url鏈接,二是從本地路徑獲取,三是通過字符串解析成html文檔
在這里,我們利用前兩種搭配使用:
先看本地是否存在需要的網頁,如果不存在就通過url獲取並保存在本地(下次就可以不需要重新從網絡加載)
訪問鏈接看到我們的網站是這樣的:
利用谷歌瀏覽右鍵檢查元素,我們注意觀察黃色標記的部分:
我們新建一個類,具體內容如下:
1 //根據url獲取數據 2 public Document getHtmlTextByUrl(String url){ 3 Document document=null; 4 try{ 5 int i=(int)(Math.random()*1000);////做一個隨機延時,防止網站屏蔽 6 while (i!=0) { 7 i--; 8 } 9 document=Jsoup.connect(url) 10 .data("query","Java") 11 .userAgent("Mozilla") 12 .cookie("auth", "token") 13 .timeout(300000).post(); 14 }catch(Exception e){ 15 e.printStackTrace(); 16 try{ 17 document=Jsoup.connect(url).timeout(5000000).get(); 18 }catch(Exception e1){ 19 e1.printStackTrace(); 20 } 21 } 22 return document; 23 } 24 25 //根據元素屬性獲取某個元素內的elements列表 26 public Elements getElementByClass(Document document,String className){ 27 Elements elements=null; 28 elements=document.select(className); 29 return elements; 30 } 31 32 public ArrayList getProvice(String url,String type){ 33 ArrayList result=new ArrayList(); 34 String classtype="."+type; 35 //從網絡上獲取網頁 36 Document document=getHtmlTextByUrl(url); 37 if (document!=null) { 38 Elements elements=getElementByClass(document,classtype);// tr的集合 39 for(Element e:elements){// 依次循環每個元素,也就是一個tr 40 if(e!=null){ 41 for(Element ec:e.children()){// 一個tr的子元素td,td內包含a標簽 42 String[] prv = new String[4]; 43 if(ec.children().first()!=null){ 44 prv[0]=url;// 原來的url 45 prv[1]=ec.children().first().ownText(); 46 System.out.println(prv[1]);//身份名稱 47 48 String ownurl=ec.children().first().attr("abs:href"); 49 prv[2]=ownurl; 50 System.out.println(prv[2]); 51 52 prv[3]=type; 53 result.add(prv); 54 } 55 } 56 } 57 } 58 } 59 return result; 60 } 61 62 public static void main(String[] args) { 63 String url="http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2015/index.html"; 64 String type="provincetr"; 65 System.out.println(new Html().getProvice(url, type)); 66 }