高德API获取省市区---python3实现

# -*- coding: utf-8 -*-
"""
Created on Thu Nov  4 15:40:25 2021
@author: 何双新
"""

import requests
import json
# 需要自己申请高德地图API
# 根据输入条件快速查找特定行政区域信息

#文档生成路径
filename='D:\\pcd.json' def get_country_pcds(keywords:str): parameters = { 'key':'732a7b196e393006246f90c3ce247559', 'keywords':keywords, 'subdistrict':3 } r = requests.get('https://restapi.amap.com/v3/config/district?parameters',params=parameters) data = r.json()['districts'][0]['districts'] #获取到所有的省 vals_sen=[] for i in data: vals_c=[] vals_qu=[] for j in i["districts"]: vals_c.append({"province_name":i["name"], "city_name":j["name"], "b_code":j["adcode"], "b_x":j["center"].split(",")[0], "b_y":j["center"].split(",")[1], "country":"China", }) for k in j["districts"]: vals_qu.append({ "province_name":i["name"], "city_name":j["name"], "district_name":k["name"], "b_code":k["adcode"], "b_x":k["center"].split(",")[0], "b_y":k["center"].split(",")[1], "country":"China" }) vals_sen.append({ "province_name":i["name"], "b_code":i["adcode"], "b_x":i["center"].split(",")[0], "b_y":i["center"].split(",")[1], "country":"China", "city_dict":vals_c, "district_dict":vals_qu }) print ('-----vals_sen-------',vals_sen) #ensure_ascii=False 解决写入到文本的中文格式是16进制问题 with open(filename,'w',encoding='utf-8') as f: json.dump(vals_sen,f,ensure_ascii=False) return get_country_pcds('中国') #output-->province

 

 

最后保存的json格式为:

 

 

posted @ 2022-09-28 15:54  何双新  阅读(240)  评论(0编辑  收藏  举报