2017-02-28 6 views
0

非常に簡単な質問ですが、私は複数の方法で修正することを試みましたが、修正するのが非常に簡単なものを渡していると思います。APIをループするときのエラーの解決方法

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をループし、各リポジトリに関する情報を印刷します。リポジトリの1つに説明がないので、その説明をスキップしたり、「No description available」と言うと、プログラムがクラッシュすることはありません。

ありがとうございました。

答えて

1

これはうまくいく可能性があります。単純なif文で空の文字列をチェックします。

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

これはあなたのために働くかもしれない:

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を返します。

関連する問題