0

出于某种原因,我得到了我正在寻找的 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

那就是我要找的网址,但是为什么它没有问题地找到它然后抛出错误?

这是来自 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}`
4

0 回答 0