当前位置: 首页 > news >正文

【行政区划获取】

行政区划获取

获取2023年的行政区划,并以 编码: 省市区 格式保存为字典方便后续调用
注:网址可能会更新,根据最新的来

# 获取并保存行政区划代码
import requests
from lxml import etree
import json

def fetch_html(url):
    """获取网页内容"""
    try:
        response = requests.get(url)
        response.raise_for_status()
        response.encoding = 'utf-8'
        return response.text
    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return None

def parse_html(html):
    """解析HTML并生成行政区划字典"""
    if not html:
        return None

    html_tree = etree.HTML(html)
    rows = html_tree.xpath('//*[text()="行政区划代码"]/../following-sibling::tr')
    
    location_dict = {}
    current_province = ''
    current_city = ''

    for row in rows:
        if not row.xpath('./td[2]/text()'):
            continue

        code = row.xpath('./td[2]/text()')[0].strip()
        name = row.xpath('./td[3]/text()')[0].replace('*', '').strip()

        if code.endswith('0000'):  # 省级
            current_province = name
            location_dict[code] = {'province': current_province, 'city': '', 'district': ''}
        elif code.endswith('00'):  # 市级
            current_city = name
            location_dict[code] = {'province': current_province, 'city': current_city, 'district': ''}
        else:  # 区县级
            location_dict[code] = {'province': current_province, 'city': current_city, 'district': name}

    return location_dict

def generate_full_address(location_dict):
    """生成完整的地址字符串"""
    finally_location_dict = {}
    for code, location in location_dict.items():
        full_address = f"{location['province']} {location['city']} {location['district']}".strip()
        finally_location_dict[code] = full_address
    return finally_location_dict

def save_to_json(data, filename):
    """将数据保存为JSON文件"""
    try:
        with open(filename, 'w+', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print(f"数据已成功保存到 {filename}")
    except IOError as e:
        print(f"文件保存失败: {e}")

def main():
    url = 'https://www.mca.gov.cn/mzsj/xzqh/2023/202301xzqh.html'
    html = fetch_html(url)
    if html:
        location_dict = parse_html(html)
        if location_dict:
            finally_location_dict = generate_full_address(location_dict)
            save_to_json(finally_location_dict, 'city_and_code.json')

if __name__ == "__main__":
    main()

# 提取编码对应省市区
# with open(r'city_and_code.json', "r", encoding="utf-8") as f:
#     dict_ = json.load(f)
# print(dict_["320507"])

相关文章:

  • 专业工具,杜绝一切垃圾残留!
  • surfaceflinger对INVALIDATE和REFRESH消息的处理
  • 解锁网络防御新思维:D3FEND 五大策略如何对抗 ATTCK
  • 突破Ajax跨域困境,解锁前端通信新姿势
  • Ubuntu20.04下各类常用软件及库安装汇总(联想Y9000P24款)
  • 【MySQL】数据库初识
  • 【计算机网络入门】初学计算机网络(四)
  • 从递归到动态规划(三维)
  • Excel工作圈小工具一个集合了大量Excel功能的绿色工具软件
  • 【Java基础】Java 中的枚举类
  • 【嵌入式】MCU开发基础知识速通
  • Qt 文件操作+多线程+网络
  • 使用Python自动生成图文并茂的网页分析报告
  • 初学者如何用 Python 写第一个爬虫?
  • 服务流程设计和服务或端口重定向及其websocket等应用示例
  • llama-factory ||启智平台
  • 快递站点管理|基于springboot校园快递站点管理设计与实现(源码+数据库+文档)
  • 头歌实验---C/C++程序设计:实验四:循环结构程序设计
  • 2024贵州大学计算机考研复试上机真题
  • 慢SQL如何定位处理?
  • 江西3人拟提名为县(市、区)长候选人
  • 国家卫健委通报:吊销肖某医师执业证书,撤销董某莹四项证书
  • 奥运“四朝元老”华天回国参赛,伤势未愈谨慎出战全国锦标赛
  • 夜读丨读《汉书》一得
  • “典孝急乐批麻蚌赢”:互联网“八字真言”与当代赛博赢学
  • 威尼斯建筑双年展总策划:山的另一边有什么在等着我们