gpt4 book ai didi

python - 使用 urllib、urllib2 和 json 模块为 Google map API 创建客户端时出现 KeyError

转载 作者:行者123 更新时间:2023-11-30 23:34:51 24 4
gpt4 key购买 nike

import urllib,urllib2
try:
import json
except ImportError:
import simplejson as json
params = {'q': '207 N. Defiance St, Archbold, OH','output': 'json', 'oe': 'utf8'}
url = 'http://maps.google.com/maps/geo?' + urllib.urlencode(params)

rawreply = urllib2.urlopen(url).read()
reply = json.loads(rawreply)
print (reply['Placemark'][0]['Point']['coordinates'][:-1])

执行此代码时,我收到错误:

回溯(最近一次调用最后一次): 文件“C:/Python27/Foundations_of_networking/search2.py”,第 11 行,位于 print (回复['地标'][0]['点']['坐标'][:-1])关键错误:“地标”

如果有人知道解决方案,请帮助我。我刚刚接触 python。

最佳答案

如果您只打印reply,您将看到以下内容:

{u'Status': {u'code': 610, u'request': u'geocode'}}

您正在使用已弃用的 API 版本。移至 v3。看一下this page顶部的通知.

我以前没有使用过这个 API,但以下内容给了我提示(摘自 here ):

New endpoint

The v3 Geocoder uses a different URL endpoint:

http://maps.googleapis.com/maps/api/geocode/output?parameters Where output can be specified as json or xml.

Developers switching from v2 may be using a legacy hostname — either maps.google.com, or maps-api-ssl.google.com if using SSL. You should migrate to the new hostname: maps.googleapis.com. This hostname can be used both over both HTTPS and HTTP.

尝试以下操作:

import urllib,urllib2
try:
import json
except ImportError:
import simplejson as json
params = {'address': '207 N. Defiance St, Archbold, OH', 'sensor' : 'false', 'oe': 'utf8'}
url = 'http://maps.googleapis.com/maps/api/geocode/json?' + urllib.urlencode(params)

rawreply = urllib2.urlopen(url).read()
reply = json.loads(rawreply)

if reply['status'] == 'OK':
#supports multiple results
for item in reply['results']:
print (item['geometry']['location'])

#always chooses first result
print (reply['results'][0]['geometry']['location'])
else:
print (reply)

上面我展示了两种访问结果的经度和纬度的方法。 for 循环将支持返回多个结果的情况。第二个只是选择第一个结果。请注意,无论哪种情况,我都会首先检查返回的状态,以确保返回真实数据。

如果您想独立访问纬度和经度,您可以这样做:

# in the for loop
lat = item['geometry']['location']['lat']
lng = item['geometry']['location']['lng']

# in the second approach
lat = reply['results'][0]['geometry']['location']['lat']
lng = reply['results'][0]['geometry']['location']['lng']

关于python - 使用 urllib、urllib2 和 json 模块为 Google map API 创建客户端时出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17867272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com