为什么在找到并打印出正确的URL之后会出现KeyError?

时间:2018-08-07 16:10:36

标签: python-3.x google-knowledge-graph

由于某种原因,我得到了所要查找的URL,但是此后,我仍然收到KeyError,并且不确定自己做错了什么。

输入:

"""Example of Python client calling Knowledge Graph Search API."""
import json
import urllib.parse
import urllib.request

api_key = 'my api key'
query = 'voi'
service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
params = {
    'query': query,
    'limit': 10,
    'indent': True,
    'key': api_key,
}
url = service_url + '?' + urllib.parse.urlencode(params)
response = json.loads(urllib.request.urlopen(url).read())
for element in response['itemListElement']:
    print(element['result']['detailedDescription']['url'])

输出:

C:\Python36\python.exe C:/Users/NikkiL/PycharmProjects/experimenting/knowledgegraph.py
Traceback (most recent call last):
https://en.wikipedia.org/wiki/Voi
  File "C:/Users/NikkiL/PycharmProjects/experimenting/knowledgegraph.py", line 18, in <module>
    print(element['result']['detailedDescription']['url'])
KeyError: 'detailedDescription'

Process finished with exit code 1

正如您从输出中看到的那样,

Traceback (most recent call last):
https://en.wikipedia.org/wiki/Voi

这是我一直在寻找的URL,但是为什么它没有问题地找到它然后抛出错误?

这是来自print(element)的数据结构:

{'@type': 'EntitySearchResult', 'result': {'@id': 'kg:/m/08wy0_', 'name': `'Voi', '@type': ['Thing', 'Place', 'City'], 'description': 'Town in Kenya', 'image': {'contentUrl': 'http://t3.gstatic.com/images?q=tbn:ANd9GcRfSu6k0uKR5Gr4VoeGH6zxZ2qsXmfbN7O-HGnd-Jy0YuSxxb6n', 'url': 'https://en.wikipedia.org/wiki/Voi'}, 'detailedDescription': {'articleBody': 'Voi is the largest town in Taita-Taveta County in southern Kenya, in the former Coast Province. It lies at the western edge of the Taru Desert, south and west of the Tsavo East National Park. The Sagala Hills are to the south. Voi is also a municipality.', 'url': 'https://en.wikipedia.org/wiki/Voi', 'license': 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'}}, 'resultScore': 38.771496}`

0 个答案:

没有答案