import urllib.request, urllib.parse, urllib.error
import json
import hashlib
import numpy as np
import pandas as pd
MyAK = ''
MySK = ''
lat=0.0
lng=0.0
#处理得到url
def get_url(name):
#GET请求 http://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
queryStr = '/geocoding/v3/?address={}&output=json&ak={}'.format(name,MyAK)
# 对queryStr进行转码,safe内的保留字符不转换
encodedStr = urllib.parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
# 在最后追加sk
rawStr = encodedStr + MySK
# 计算sn
sn = (hashlib.md5(urllib.parse.quote_plus(rawStr).encode("utf8")).hexdigest())
#由于URL里面含有中文,所以需要用parse.quote进行处理,然后返回最终可调用的url
url = urllib.parse.quote("http://api.map.baidu.com" + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")
print('URL:', url)
return url
#得到json数据
def get_json(url):
# 从API读取数据
req = urllib.request.urlopen(url)
res = req.read().decode()
# 解析数据
try:
# 将 JSON 对象转换为 Python 字典
json_data = json.loads(res)
except:
json_data = "地址未知"
if not json_data or 'status' not in json_data or json_data['status'] != 0:
print('json数据获取失败',json_data['status'])
'''else:
#输出Json数据
print(json.dumps(json_data, indent=4, ensure_ascii=False))'''
return json_data
# 获取经纬度坐标
def get_lnglat(json_data):
#Python中定义函数时,若想在函数内部对函数外的变量进行操作,就需要在函数内部声明其为global
global lat,lng
lat = json_data["result"]["location"]["lat"]
lng = json_data["result"]["location"]["lng"]
# print('纬度', lat, '经度', lng)
def get_url2(lat,lng):
#GET请求 http://api.map.baidu.com/reverse_geocoding/v3/?ak=您的ak&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194
queryStr = '/reverse_geocoding/v3/?ak={}&output=json&coordtype=wgs84ll&location={},{} '.format(MyAK,str(lat),str(lng))
# 对queryStr进行转码,safe内的保留字符不转换
encodedStr = urllib.parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
# 在最后追加sk
rawStr = encodedStr + MySK
# 计算sn
sn = (hashlib.md5(urllib.parse.quote_plus(rawStr).encode("utf8")).hexdigest())
#由于URL里面含有中文,所以需要用parse.quote进行处理,然后返回最终可调用的url
url = urllib.parse.quote("http://api.map.baidu.com" + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")
#print('URL:', url)
return url
# 解析Json数据
def get_info(json_data):
if json_data != "地址未知":
province = json_data.get("result", {}).get("addressComponent", {}).get("province", "未知")
city=json_data["result"]["addressComponent"]["city"]
district=json_data["result"]["addressComponent"]["district"]
# adcode=json_data["result"]["addressComponent"]["adcode"]
# print("地理:",province+city+district)
result = province+city+district
else:
result = json_data
return json_data
# print("行政代码:"+adcode)
if __name__ == '__main__':
#得到经纬度
# 读取csv文件单位地区数据
df = pd.read_csv("result_table01.csv",encoding='utf-8')
data = df[['单位']]
data = data.fillna("0")
data_array = np.array(data.stack()) # 首先将pandas读取的数据转化为array
data_list = data_array.tolist() # 然后转化为list形式
#print(data_list)
print(len(data_list))
# 将各个单位名称存储为一个列表形式
url = []
for i in range(0,len(data_list)):
result =data_list[i]
#print(result)
url.append(result)
# print(url)
rr = []
city = []
province = []
direct = []
for i in range(0, len(url)):
try:
uu = get_url(url[i])
json_data = get_json(uu)
status = json_data.get('status')
if status == 0:
lnglat = get_lnglat(json_data)
uu2 = get_url2(lat, lng)
json_data = get_json(uu2)
p = json_data.get("result", {}).get("addressComponent", {}).get("province", "未知")
c=json_data["result"]["addressComponent"]["city"]
d=json_data["result"]["addressComponent"]["district"]
province.append(p)
city.append(c)
direct.append(d)
elif status in [1, 2, 3]:
print(f"跳过处理,状态码为 {status}")
province.append(" ")
city.append(" ")
direct.append(" ")
else:
print(f"未处理的状态码:{status}")
province.append(" ")
city.append(" ")
direct.append(" ")
except Exception as e:
print(f"处理数据时发生异常:{e}")
province.append(" ")
city.append(" ")
direct.append(" ")
df['省'] = province
df['市'] = city
df['县'] = direct
df.to_csv("result_table05.csv", index=False)
print("添加省市县成功!")
标签:省市,get,url,数据,json,result,print,data
From: https://www.cnblogs.com/lin513/p/18095626