抓取全國行政機構(省市縣鎮村)

package com.jsoup;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupRegion {
	/** 整數 */
	private static final String V_INTEGER = "^-?[1-9]\\d*$";

	class Region {
		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getParentId() {
			return parenId;
		}

		public void setParentId(int parenId) {
			this.parenId = parenId;
		}

		public String getType() {
			return type;
		}

		public void setType(String type) {
			this.type = type;
		}

		private String code;
		private String name;
		private String type;// 鄉鎮類型
		private int parenId;

	}

	/**
	 * @說明: url2Document
	 * @param @param url
	 * @param @return
	 * @param @throws IOException
	 * @return Document
	 * @throws
	 */
	public static Document url2Doc(String url) throws IOException {
		// 此種方式403
		// return Jsoup.connect(url).get();
		// return Jsoup.connect(url).timeout(600 * 1000)
		// .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36").get();
		//
		return Jsoup.connect(url).timeout(600 * 1000).get();
	}

	/**
	 * 驗證是否是整數
	 * 
	 * @param value
	 *            要驗證的字符串 要驗證的字符串
	 * @return 若是是符合格式的字符串,返回 <b>true </b>,不然爲 <b>false </b>
	 */
	public static boolean Integer(String value) {
		return match(V_INTEGER, value);
	}

	/**
	 * @param regex
	 *            正則表達式字符串
	 * @param str
	 *            要匹配的字符串
	 * @return 若是str 符合 regex的正則表達式格式,返回true, 不然返回 false;
	 */
	private static boolean match(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	/**
	 * 追加文件:使用FileWriter
	 * 
	 * @param fileName
	 * @param content
	 */
	public static void appendFile(String fileName, String content) {
		FileWriter writer = null;
		try {
			// 打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
			writer = new FileWriter(fileName, true);
			writer.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @說明: 獲取省份
	 * @param @param url
	 * @param @return
	 * @param @throws IOException
	 * @return List<Region>
	 * @throws
	 */
	private static List<Region> getProvince(String url) throws IOException {
		List<Region> list = new ArrayList<Region>();
		Document doc = url2Doc(url);
		Elements proviceTr = doc.getElementsByAttributeValue("class", "provincetr");// 經過css獲取tr
		for (Element e : proviceTr) {
			Elements tds = e.select("a[href]");
			for (Element element : tds) {
				Region region = new JsoupRegion().new Region();
				// region.setCode("13");
				region.setCode(element.attr("href").substring(0, 2));
				region.setName(element.text().replaceAll("<br />", ""));
				region.setType("");
				region.setParentId(0);
				list.add(region);
			}
		}
		return list;
	}

	/**
	 * @說明: 獲取省份下的市
	 * @param @param url
	 * @param @return
	 * @param @throws IOException
	 * @return List<Region>
	 * @throws
	 */
	private static List<Region> getCity(String url) throws IOException {
		List<Region> list = new ArrayList<Region>();
		Document doc = url2Doc(url);
		Elements proviceTr = doc.getElementsByAttributeValue("class", "citytr");// 經過css獲取tr
		for (Element e : proviceTr) {
			Elements tds = e.select("a[href]");
			for (Element element : tds) {
				if (Integer(element.text())) {
					continue;
				}
				Region region = new JsoupRegion().new Region();
				String code = element.attr("href").substring(3, 7);
				region.setCode(code);
				region.setName(element.text());
				region.setParentId(Integer.valueOf(code.substring(0, 2)));
				region.setType("");
				list.add(region);
			}
		}
		return list;
	}

	/**
	 * @說明: 縣
	 * @param @param url
	 * @param @return
	 * @param @throws IOException
	 * @return List<Region>
	 * @throws
	 */
	private static List<Region> getCounty(String url) throws IOException {
		List<Region> list = new ArrayList<Region>();
		Document doc = url2Doc(url);
		Elements proviceTr = doc.getElementsByAttributeValue("class", "countytr");// 經過css獲取tr
		for (Element e : proviceTr) {
			Elements tds = e.select("a[href]");
			for (Element element : tds) {
				if (Integer(element.text())) {
					continue;
				}
				Region region = new JsoupRegion().new Region();
				String code = element.attr("href").substring(3, 9);
				region.setCode(code);
				region.setName(element.text());
				region.setParentId(Integer.valueOf(code.substring(0, 4)));
				region.setType("");
				list.add(region);
			}
		}
		return list;
	}

	/**
	 * @說明: 鎮
	 * @param @param url
	 * @param @return
	 * @param @throws IOException
	 * @return List<Region>
	 * @throws
	 */
	private static List<Region> getTown(String url) throws IOException {
		List<Region> list = new ArrayList<Region>();
		Document doc = url2Doc(url);
		Elements proviceTr = doc.getElementsByAttributeValue("class", "towntr");// 經過css獲取tr
		for (Element e : proviceTr) {
			Elements tds = e.select("a[href]");
			for (Element element : tds) {
				if (Integer(element.text())) {
					continue;
				}
				Region region = new JsoupRegion().new Region();
				String code = element.attr("href").substring(3, 12);
				region.setCode(code);
				region.setName(element.text());
				region.setParentId(Integer.valueOf(code.substring(0, 6)));
				region.setType("");
				list.add(region);
			}
		}
		return list;
	}

	/**
	 * @說明: 村
	 * @param @param url
	 * @param @return
	 * @param @throws IOException
	 * @return List<Region>
	 * @throws
	 */
	private static List<Region> getVillage(String url) throws IOException {
		List<Region> list = new ArrayList<Region>();
		Document doc = url2Doc(url);
		Elements proviceTr = doc.getElementsByAttributeValue("class", "villagetr");// 經過css獲取tr
		for (Element e : proviceTr) {
			Elements trs = e.select("tr");
			for (Element element : trs) {
				Elements tds = element.select("td");
				Region region = new JsoupRegion().new Region();
				for (Element element2 : tds) {
					String value = element2.text();
					if (Integer(value) && value.length() == 3) {
						region.setType(element2.text());
					}
					if (Integer(value) && value.length() > 3) {
						region.setCode(value);
						region.setParentId(Integer.valueOf(value.substring(0, 9)));
					} else {
						region.setName(value);
					}

				}
				list.add(region);

			}
		}
		return list;
	}

	public static void main(String[] args) throws IOException {
		List<Region> all = new ArrayList<Region>();
		List<Region> province = getProvince("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2013/index.html");
		all.addAll(province);
		List<String> done = new ArrayList<String>();//用來存已經抓取過的省份
		for (Region regionProvince : province) {// 遍歷省
			if (done.contains(regionProvince.getCode())) {
				continue;
			}
			System.out.println(regionProvince.getCode() + regionProvince.getName());
			appendFile("E:/" + regionProvince.getCode() + regionProvince.getName() + ".txt", regionProvince.getCode() + "||" + regionProvince.getName() + "||"
					+ regionProvince.getParentId() + "||" + regionProvince.getType() + "\r\n");

			List<Region> city = getCity("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2013/" + regionProvince.getCode() + ".html");
			for (Region regionCity : city) {// 遍歷市
				System.out.println(regionCity.getCode() + "||" + regionCity.getName());
				appendFile("E:/" + regionProvince.getCode() + regionProvince.getName() + ".txt", regionCity.getCode() + "||" + regionCity.getName() + "||"
						+ regionCity.getParentId() + "||" + regionCity.getType() + "\r\n");

				List<Region> county = getCounty("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2013/" + regionProvince.getCode() + "/"
						+ regionCity.getCode() + ".html");
				all.addAll(county);
				for (Region regionCounty : county) {// 遍歷縣
					appendFile("E:/" + regionProvince.getCode() + regionProvince.getName() + ".txt", regionCounty.getCode() + "||" + regionCounty.getName()
							+ "||" + regionCounty.getParentId() + "||" + regionCounty.getType() + "\r\n");

					List<Region> town = getTown("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2013/" + regionProvince.getCode() + "/"
							+ regionCity.getCode().substring(2, 4) + "/" + regionCounty.getCode() + ".html");
					all.addAll(town);
					for (Region regionTown : town) {// 遍歷鎮
						appendFile("E:/" + regionProvince.getCode() + regionProvince.getName() + ".txt", regionTown.getCode() + "||" + regionTown.getName()
								+ "||" + regionTown.getParentId() + "||" + regionTown.getType() + "\r\n");

						List<Region> village = getVillage("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2013/" + regionProvince.getCode() + "/"
								+ regionCity.getCode().substring(2, 4) + "/" + regionCounty.getCode().substring(4, 6) + "/" + regionTown.getCode() + ".html");
						all.addAll(village);
						for (Region regionVillage : village) {// 遍歷村
							appendFile(
									"E:/" + regionProvince.getCode() + regionProvince.getName() + ".txt",
									regionVillage.getCode() + "||" + regionVillage.getName() + "||" + regionVillage.getParentId() + "||"
											+ regionVillage.getType() + "\r\n");

						}
					}

				}

			}
		}
	}
}
相關文章
相關標籤/搜索