在使用urllib,urllib2和json模块为Google的Maps API创建客户端时获取KeyError


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 行,在 打印(回复["地标"][0]["点"]["坐标"][:-1](键错误:"地标">

如果有人知道解决方案,请帮助我。我只是对python的新手。

如果你只打印reply你会看到这个:

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

您正在使用已弃用的 API 版本。移至 v3。请查看本页顶部的通知。

我以前没有使用过这个 API,但以下内容告诉我(从这里获取(:

新建终结点

v3 地理编码器使用不同的 URL 端点:

http://maps.googleapis.com/maps/api/geocode/output?parameters 地点 输出可以指定为 JSON 或 XML。

从 v2 切换的开发人员可能使用旧主机名 - 要么 maps.google.com,如果使用 SSL,则 maps-api-ssl.google.com。你应该 迁移到新主机名:maps.googleapis.com。此主机名可以是 同时通过HTTPS和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循环将支持返回多个结果的情况。第二个只是选择第一个结果。请注意,无论哪种情况,我都会首先检查返回的status,以确保返回真实数据。

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

# 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']

只需打印出原始回复,查看它有哪些键,然后访问这些键,如果您这样做:

print (reply["Status"]), 

您将获得:

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

您的整个 JSON 如下所示:

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

因此,如果您想访问代码,只需执行以下操作:

print(reply["Status"]["code"])

当您尝试访问对象上不存在的键时,会引发 KeyError 异常。

我以原始回复打印响应文本:

>>> print rawreply
... {
      "Status": {
        "code": 610,
        "request": "geocode"
      }
    }

所以问题是你没有收到预期的响应,那里没有"地标"键,因此例外。

谷歌地图API上寻找代码610的含义,也许你没有进行正确的查询,或者你必须在访问它之前检查响应。

最新更新