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

【行政区划获取】

行政区划获取

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

# 获取并保存行政区划代码
import requests
from lxml import etree
import jsondef fetch_html(url):"""获取网页内容"""try:response = requests.get(url)response.raise_for_status()response.encoding = 'utf-8'return response.textexcept requests.RequestException as e:print(f"请求失败: {e}")return Nonedef parse_html(html):"""解析HTML并生成行政区划字典"""if not html:return Nonehtml_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()'):continuecode = row.xpath('./td[2]/text()')[0].strip()name = row.xpath('./td[3]/text()')[0].replace('*', '').strip()if code.endswith('0000'):  # 省级current_province = namelocation_dict[code] = {'province': current_province, 'city': '', 'district': ''}elif code.endswith('00'):  # 市级current_city = namelocation_dict[code] = {'province': current_province, 'city': current_city, 'district': ''}else:  # 区县级location_dict[code] = {'province': current_province, 'city': current_city, 'district': name}return location_dictdef 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_addressreturn finally_location_dictdef 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"])
http://www.lryc.cn/news/545815.html

相关文章:

  • 【深入剖析:机器学习、深度学习与人工智能的关系】
  • Docker 学习(一)
  • flink web ui未授权漏洞处理
  • 【vue-echarts】——03.配置项---tooltip
  • 【弹性计算】弹性裸金属服务器和神龙虚拟化(二):适用场景
  • 提升系统效能:从流量控制到并发处理的全面解析
  • 计算机毕业设计SpringBoot+Vue.js贸易行业CRM系统(源码+文档+PPT+讲解)
  • 从头开始学SpringBoot—02ssmp整合及案例
  • 0301 leetcode - 1502.判断是否能形成等差数列、 682.棒球比赛、657.机器人能否返回原点
  • Vulnhub靶机——AI-WEB-1
  • 无人系统:未来科技的智能化代表
  • 在Docker中部署DataKit最佳实践
  • 进程的状态 ─── linux第11课
  • MySQL数据库基本概念
  • 什么是 jQuery
  • Redis Desktop Manager(Redis可视化工具)安装及使用详细教程
  • [KEIL]单片机技巧 01
  • 云原生监控篇——全链路可观测性与AIOps实战
  • C# 13与.NET 9革新及工业开发应用
  • Linux系统之DHCP网络协议
  • 【Linux】【网络】不同子网下的客户端和服务器通信其它方式
  • 【C++/数据结构】栈
  • Qt 对象树详解:从原理到运用
  • 【软路由】ImmortalWrt 编译指南:从入门到精通
  • 【智能音频新风尚】智能音频眼镜+FPC,打造极致听觉享受!【新立电子】
  • 第2章 windows故障排除(网络安全防御实战--蓝军武器库)
  • 深度学习笔记——线性回归的从0开始实现
  • 配置Spring Boot中的Jackson序列化
  • AWS跨账号服务全解析:安全共享资源的最佳实践
  • Rust~String、str、str、String、Box<str> 或 Box<str>