star wars api => IndexError: list index out of range error

star wars api => IndexError: list index out of range error

我正在使用来自 http://swapi.co/api/ 的星球大战 API。我可以很好地连接到它,我的项目进展顺利。但是,我 运行 进入以下错误信息:IndexError: list index out of range error。查看其他堆栈溢出问题,似乎这可能是一个错误。我不确定如何针对我的程序修复它。这是代码:

url = ('http://swapi.co/api/' + str(view))
#Setting up a get request to pull the data from the URL
r = requests.get(url)
if r.status_code == 200:
   print("status_code", r.status_code)
else:
  print("Sorry it appears your connection failed!")

#Storing the API response in a variable
response_dict = r.json()
print("There are currently", response_dict['count'], "items to view")

repo_dicts = response_dict['results']

num = 0
while num < response_dict['count']:
  if view == 'films':
    repo_dict = repo_dicts[num]['title']
    print(str(num) + " " + repo_dict)
  elif view == 'starships':
    repo_dict = repo_dicts[num]['name']
    print(str(num) + " " + repo_dict)
  num += 1

现在给我问题的那一行是在 elif view == 'starships' 区域。实际上,如果你去 API 你可以看到某些类别,如电影、人物、星际飞船等。所有类别,除了电影,都有超过 10 种东西。我还注意到,如果我转到 http://swapi.co/api/starships/4/,将找不到任何详细信息。某些类别没有数据这一事实是否会导致我的问题?感谢您的任何见解!!

这是回溯错误消息:

Traceback (most recent call last):
  File "main.py", line 102, in <module>
  main()
  File "main.py", line 98, in main
  began()
  File "main.py", line 87, in began
  connect(view)
  File "main.py", line 31, in connect
  repo_dict = repo_dicts[num]['name']
 IndexError: list index out of range

像这样使用 foreach 循环遍历您的结果:

for item in repo_dicts:
    if view == 'films':
        repo_dict = item['title']
        print(str(num) + " " + repo_dict)
    elif view == 'starships':
        repo_dict = item['name']
        print(str(num) + " " + repo_dict)

原因是 api returns response_dict['results'] 中有 10 个项目,但 response_dict['count'] 是 37 个。请参阅 api 文档了解发生这种情况的原因。我猜这是可能发生的分页。