翼度科技»论坛 编程开发 python 查看内容

爬取行政区划代码

11

主题

11

帖子

33

积分

新手上路

Rank: 1

积分
33
爬取国家统计局统计用区划代码和城乡划分代码 2023 版

python 实现
一、打开国家统计局官网

https://www.stats.gov.cn/sj/tjbz/qhdm/

二、分析每一级URL找到规律

省级:https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/index.html
地市级:https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/61.html 61为陕西编码
区县级:https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/61/6101.html

找到规律 当前路径+href 路径即可跳入下一级
打码
  1. import json
  2. import time
  3. import requests
  4. from bs4 import BeautifulSoup
  5. main_url = "https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023"
  6. class area_code:
  7.     name = ""
  8.     code = ""
  9.     url = ""
  10.     child = []
  11.     urban_rural_type = 0
  12.     lng = 0
  13.     lat = 0
  14.     def __init__(self, name, code, url, child, urban_rural_type=0):
  15.         self.name = name
  16.         self.code = code
  17.         self.url = url
  18.         self.child = child
  19.         self.urban_rural_type = urban_rural_type
  20.         self.lng = 0
  21.         self.lat = 0
  22. # 爬取全国统计用区划代码和城乡划分代码
  23. # pip install beautifulsoup4
  24. def get_code(suffix_url="index.html"):
  25.     _province_url = "{}/{}".format(main_url, suffix_url)
  26.     response = requests.get(_province_url)
  27.     response.encoding = "utf-8"
  28.     _html = response.text
  29.     _soup = BeautifulSoup(_html, "html.parser")
  30.     _province_code = {}
  31.     for a in _soup.find_all("a"):
  32.         if a.get("href") and a.get("href").endswith(".html"):
  33.             _province_code[a.text] = a.get("href")
  34.     return _province_code
  35. def get_child_code(_url, _parent_url=None, _retry=3):
  36.     """
  37.     输出 [{name:"呼和浩特市", code:"150100000000", url:"15/1501.html"},{name:"包头市", code:"150200000000", url:"15/1502.html"}]
  38.     :param _parent_url: 父级url
  39.     :param _retry: 重试次数
  40.     :param _url: 当前url
  41.     :return:
  42.     """
  43.     _city_code = []
  44.     if _parent_url is not None and len(_parent_url) > 0:
  45.         # 截取最后一个"/"之前的字符串
  46.         _parent_path = _parent_url.rsplit("/", 1)[0]
  47.         _req_url = "{}/{}".format(_parent_path, _url)
  48.     else:
  49.         _req_url = "{}/{}".format(main_url, _url)
  50.     try:
  51.         response = requests.get(_req_url)
  52.     except Exception as e:
  53.         if _retry > 0:
  54.             time.sleep(1)
  55.             print("请求出错:{},第{}次重试".format(e, 4 - _retry))
  56.             return get_child_code(_url, _parent_url, _retry - 1)
  57.         else:
  58.             raise e
  59.     response.encoding = "utf-8"
  60.     _html = response.text
  61.     _soup = BeautifulSoup(_html, "html.parser")
  62.     # class_="citytr" or class_="towntr" or class_="countytr" or class_="villagetr"
  63.     for tr in _soup.find_all("tr", class_=["citytr", "towntr", "countytr"]):
  64.         _tds = tr.find_all("td")
  65.         print("开始处理 - {}".format(_tds[1].text))
  66.         _child_url = ""
  67.         if _tds[0].find("a") is not None and _tds[0].find("a").get("href") is not None:
  68.             _child_url = _tds[0].find("a").get("href")
  69.             if _child_url.endswith(".html"):
  70.                 _child = get_child_code(_child_url, _req_url)
  71.                 _city_code.append(area_code(_tds[1].text, _tds[0].text, _child_url, _child))
  72.         else:
  73.             _city_code.append(area_code(_tds[1].text, _tds[0].text, _child_url, []))
  74.     for tr in _soup.find_all("tr", class_=["villagetr"]):
  75.         _tds = tr.find_all("td")
  76.         code = _tds[0].text
  77.         urban_rural_type = _tds[1].text
  78.         name = _tds[2].text
  79.         _city_code.append(area_code(name, code, "", [], urban_rural_type))
  80.     return _city_code
  81. def get_province_list():
  82.     """
  83.     # 获取省份、直辖市、自治区代码
  84.     :return:
  85.     """
  86.     province_map = get_code()
  87.     _province_list = []
  88.     for _name, _url in province_map.items():
  89.         _province_list.append(area_code(_name, _url.split(".")[0], _url, []))
  90.     return _province_list
  91. if __name__ == '__main__':
  92.     province_list = get_province_list()
  93.     # 获取市级代码
  94.     for province in province_list:
  95.         print("开始处理 - {}".format(province.name))
  96.         city_code = get_child_code(province.url)
  97.         province.child = city_code
  98.     # 输出到文件json
  99.     with open("area_code.json", "w", encoding="utf-8") as f:
  100.         f.write(json.dumps(province_list, default=lambda obj: obj.__dict__, ensure_ascii=False))
复制代码
缺陷


  • json格式太大了,建议直接入库或者生成cvs

  • 不支持退出续爬,后续完善....

来源:https://www.cnblogs.com/bigroc/p/18037559
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具