1. 程式人生 > >爬取資料省市縣鎮村

爬取資料省市縣鎮村

package aa;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
 * 全國省市縣鎮村資料爬取
 * @author liushaofeng
 * @date 2015-10-11 上午12:19:39
 * @version 1.0.0
 */
public class JsoupTest
{
    private static Map<Integer, String> cssMap = new HashMap<Integer, String>();
    static
    {
        cssMap.put(1, "provincetr");// 省
        cssMap.put(2, "citytr");// 市
        cssMap.put(3, "countytr");// 縣
        cssMap.put(4, "towntr");// 鎮
        cssMap.put(5, "villagetr");// 村
    }
    public static void main(String[] args) throws Exception
    {
        int level = 1;
        // 獲取全國各個省級資訊
        Document connect = connect("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/");
        Elements rowProvince = connect.select("tr." + cssMap.get(level));
        for (Element provinceElement : rowProvince)// 遍歷每一行的省份城市
        {
            Elements select = provinceElement.select("a");
            for (Element province : select)// 每一個省份(四川省)
            {
                parseNextLevel(province, level + 1);
            }
        }
    }
  private static void parseNextLevel(Element parentElement, int level) throws Exception
    {
        try
        {
            Thread.sleep(2);//睡眠一下,否則可能出現各種錯誤狀態碼
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        Document doc = connect(parentElement.attr("abs:href"));
        if (doc != null)
        {
            Elements newsHeadlines = doc.select("tr." + cssMap.get(level));//
            // 獲取表格的一行資料
            for (Element element : newsHeadlines)
            {
                printInfo(element, level + 1);
                Elements select = element.select("a");// 在遞迴呼叫的時候,這裡是判斷是否是村一級的資料,村一級的資料沒有a標籤
                if (select.size() != 0)
                {
                    parseNextLevel(select.last(), level + 1);
                }
            }
        }
    }
    /**
     * 寫一行資料到資料檔案中去
     * @param element 爬取到的資料元素
     * @param level 城市級別
     * @throws Exception 
     */
    private static void printInfo(Element element, int level) throws Exception
    {
       
String value=element.select("td").last().text();
        String code=element.select("td").first().text();
        System.out.println(code+","+value+","+level);
    }

    private static Document connect(String url)
    {
        if (url == null || url.isEmpty())
        {
            throw new IllegalArgumentException("The input url('" + url + "') is invalid!");
        }
        try
        {
            return Jsoup.connect(url).timeout(100 * 1000).get();
        } catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }
}