在API中循环时如何克服错误

2024-09-30 08:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

非常简单的问题,我已经尝试了多种方法来解决,但我认为我传递了一些非常容易解决的问题。你知道吗

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'])

在githubapi中循环执行大多数明星项目,并打印每个存储库的信息。其中一个respository没有描述,所以我如何跳过该描述或说“没有可用的描述”,同时又不让我的程序崩溃。你知道吗

谢谢。你知道吗


Tags: theinapiurlinformationresponsecountcode
2条回答

这也许对你有用。只是一个简单的if语句来检查空字符串。你知道吗

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

这可能适合您:

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。你知道吗

相关问题 更多 >

    热门问题