import json from urllib.request import urlopen from urllib.parse import quote import openpyxl # 定义函数 def Getlngat(address): url = 'http://api.map.baidu.com/geocoding/v3/' output = 'json' ak = '**************' # API密钥(百度开发者平台) add = quote(address) url = url + '?' + 'address=' + add + '&output=' + output + '&ak=' +ak # 拼接url req = urlopen(url) res = req.read().decode() # 将其他编码的字符串解码成unicode temp = json.loads(res) # 对json数据进行分析 return temp # 解析 def Analy(file_path): wb =openpyxl.load_workbook(file_path) ws = wb.active ws.cell(1,2).value='纬度' ws.cell(1,3).value='经度' for i in range(2,ws.max_row+1): try: # 异常捕获发生异常的坐标,不影响后续地点坐标获取 address = ws.cell(i,1).value lng = Getlngat(address)['result']['location']['lng'] # 获取经度 lat = Getlngat(address)['result']['location']['lat'] # 获取纬度 ws.cell(i,2).value = round(lng,3) # 写入经度,并保留3为小数 ws.cell(i,3).value = round(lat,3) # 写入纬度,并保留3位小数 print(address,lng,lat) except: ws.cell(i,4).value = "该地点目前未能获取,请重新尝试" wb.save(file_path) # 主函数 Analy(file_path=r'D:\PyCharm\坐标抓取\地点坐标.xlsx')
标签:经纬度,url,value,cell,获取,ws,address,lng From: https://www.cnblogs.com/xujunhui/p/17115274.html