Почему я получаю KeyError ПОСЛЕ того, как он находит и печатает URL-адрес очень хорошо?
По какой-то причине я получаю 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, который я искал, но почему он находит его без проблем, а затем выдает ошибку?
Это структура данных из печати (элемент):
{'@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}`