为什么我会犯一个关键错误?我已经使用第一个id检查了站点,它有一个“后代”键。提前谢谢。
Traceback (most recent call last):
File "c:\Users\Ronel_Priela\Desktop\Python\Crash_course\ch17_working_w_api\hn_submissions.py", line 24, in <module>
'comments': id_dictionary['descendants'],
KeyError: 'descendants'这是我的密码:
from operator import itemgetter
import requests
#API call
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print(r.status_code)
#Storing response
response_dicts = r.json()
#Calling another API for each id
dictionary_profiles = []
for id in response_dicts[:30]:
url = f"https://hacker-news.firebaseio.com/v0/item/{id}.json"
r=requests.get(url)
id_dictionary = r.json()
print(f'ID: {id} Status: {r.status_code}')
##Create dictionary profiles for each id
dictionary_profile = {
'title': id_dictionary['title'],
'hn_link': f"https://news.ycombinator.com/item?id={id}",
'comments': id_dictionary['descendants'],
}
dictionary_profiles.append(dictionary_profile)
print(dictionary_profiles)这是打印id_dictionary的结果,我得到了我期望的结果。
{'by': 'signa11', 'descendants': 5, 'id': 29860951, 'kids': [29861081, 29861176, 29861155, 29861086, 29861179], 'score': 13, 'time': 1641711518, 'title': 'Literate programming: Knuth is doing it wrong (2014)', 'type': 'story', 'url': 'http://akkartik.name/post/literate-programming'}发布于 2022-01-09 07:44:50
以下网站没有'descendants'键(这是列表中的第27个网站):
url = "https://hacker-news.firebaseio.com/v0/item/29856193.json"内容如下:
{"by":"festinalente","id":29856193,“记分”:1,"time":1641675620,"title":"Finley (YC W21),在英语和销售中招聘金融科技基础设施“,"type":"job","url":"https://www.finleycms.com/careers/"}”
您可以使用dict.get方法来避免任何错误。如果指定的键在字典中,则dict.get方法返回指定键的值;如果不返回,默认情况下不返回任何值。因此,如果您按照下面的方式更改构造dictionary_profile的代码,您的代码就会正常工作(没有'title'或'descendants'键的网站在dictionary_profile中没有这些键)。
dictionary_profile = {
'title': id_dictionary.get('title'),
'hn_link': f"https://news.ycombinator.com/item?id={id}",
'comments': id_dictionary.get('descendants'),
}https://stackoverflow.com/questions/70639201
复制相似问题