【问题标题】:How to get through error when looping through API循环通过API时如何解决错误
【发布时间】:2017-02-28 02:46:33
【问题描述】:

非常简单的问题,我尝试了多种方法来解决,但我认为我忽略了一些非常容易解决的问题。

import requests

# Make an API call and store the response.
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)

# Store API response in a variable.
response_dict = r.json()
print("Total respositories:", response_dict['total_count'])

# Explore information about the respositories.
repo_dicts = response_dict['items']
print("Respositories returned:", len(repo_dicts))

print("\nSelected information about each respository:")
for repo_dict in repo_dicts:

    print('\nName:', repo_dict['name'])
    print('Owner:', repo_dict['owner']['login'])
    print('Stars:', repo_dict['stargazers_count'])
    print('Respository:', repo_dict['html_url'])
    print('Description:', repo_dict['description'])

循环通过 github api 获取大多数已加星标的项目,并打印有关每个存储库的信息。其中一个存储库没有描述,那么我将如何跳过该描述或说“没有可用的描述”,同时不会让我的程序崩溃。

谢谢。

【问题讨论】:

    标签: python api github


    【解决方案1】:

    这可能对你有用。只是一个简单的 if 语句来检查一个空字符串。

    for repo_dict in repo_dicts:
        ...
        if not repo_dict['description']:
            print('No description')
        else:
            print('Description:', repo_dict['description'])
    

    【讨论】:

      【解决方案2】:

      这可能对你有用:

      for repo_dict in repo_dicts:
      
          print('\nName:', repo_dict.get('name', None))
          print('Owner:', repo_dict['owner'].get('login', None))
          print('Stars:', repo_dict.get('stargazers_count', None))
          print('Respository:', repo_dict.get('html_url', None))
          print('Description:', repo_dict.get('description', None))
      

      如果键的值为空,则返回None。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-01
        • 2021-05-23
        • 2020-03-07
        • 2022-09-22
        • 1970-01-01
        • 2012-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多