2017-04-10 8 views
0

私は、redditのapiを使って、別のサブディスクリートの最初のページとそれらの上昇している投稿を調べるために、正常に動作している次のpythonコードを持っています。PythonでReddit APIを使用するとき、散発的なKeyError: 'data'を避けるにはどうすればよいですか?

from pprint import pprint 
import requests 
import json 
import datetime 
import csv 
import time 

subredditsToScan = ["Arts", "AskReddit", "askscience", "aww", "books", "creepy", "dataisbeautiful", "DIY", "Documentaries", "EarthPorn", "explainlikeimfive", "food", "funny", "gaming", "gifs", "history", "jokes", "LifeProTips", "movies", "music", "pics", "science", "ShowerThoughts", "space", "sports", "tifu", "todayilearned", "videos", "worldnews"] 

ofilePosts = open('posts.csv', 'wb') 
writerPosts = csv.writer(ofilePosts, delimiter=',') 

ofileUrls = open('urls.csv', 'wb') 
writerUrls = csv.writer(ofileUrls, delimiter=',') 

for subreddit in subredditsToScan: 
    front = requests.get(r'http://www.reddit.com/r/' + subreddit + '/.json') 
    rising = requests.get(r'http://www.reddit.com/r/' + subreddit + '/rising/.json') 

    front.text 
    rising.text 

    risingData = rising.json() 
    frontData = front.json() 

    print(len(risingData['data']['children'])) 
    print(len(frontData['data']['children'])) 
    for i in range(0, len(risingData['data']['children'])): 
     author = risingData['data']['children'][i]['data']['author'] 
     score = risingData['data']['children'][i]['data']['score'] 
     subreddit = risingData['data']['children'][i]['data']['subreddit'] 
     gilded = risingData['data']['children'][i]['data']['gilded'] 
     numOfComments = risingData['data']['children'][i]['data']['num_comments'] 
     linkUrl = risingData['data']['children'][i]['data']['permalink'] 
     timeCreated = risingData['data']['children'][i]['data']['created_utc'] 

     writerPosts.writerow([author, score, subreddit, gilded, numOfComments, linkUrl, timeCreated]) 
     writerUrls.writerow([linkUrl]) 



    for j in range(0, len(frontData['data']['children'])): 
     author = frontData['data']['children'][j]['data']['author'].encode('utf-8').strip() 
     score = frontData['data']['children'][j]['data']['score'] 
     subreddit = frontData['data']['children'][j]['data']['subreddit'].encode('utf-8').strip() 
     gilded = frontData['data']['children'][j]['data']['gilded'] 
     numOfComments = frontData['data']['children'][j]['data']['num_comments'] 
     linkUrl = frontData['data']['children'][j]['data']['permalink'].encode('utf-8').strip() 
     timeCreated = frontData['data']['children'][j]['data']['created_utc'] 

     writerPosts.writerow([author, score, subreddit, gilded, numOfComments, linkUrl, timeCreated]) 
     writerUrls.writerow([linkUrl]) 

それがうまく機能し、正確にデータを掻き取るが、それは常に一見ランダムに、中断、および実行時のクラッシュを持っている、と言ってます:

Traceback (most recent call last): 
    File "dataGather1.py", line 27, in <module> 
    for i in range(0, len(risingData['data']['children'])): 
KeyError: 'data' 

私はこのエラーがで発生している理由はわかりません一貫していない。おそらく私はAPIをあまりにも多く呼び出すのでアクセスできなくなったと思っていたので、私のコードで眠りにつきましたが、それは助けになりませんでした。何か案は?

答えて

1

APIからの応答にデータがない場合、ディクショナリにキーデータがないため、一部のサブディレクトリでkeyErrorが発生します。試しキャッチを使用する必要があります。

0

解析しているjsonに 'data'要素が含まれていません。したがって、エラーが発生します。私はあなたの勘が正しいと思う。これはおそらくレート制限、またはあなたが隠れた/削除されたエントリを求めていることでしょう。

Redditはniceを再生せずにAPIにアクセスすることについて非常に厳しいです。つまり、あなたのアプリケーションを登録して、意味のあるユーザエージェントをあなたのリクエストに使うべきであることを意味します。この種のものには、おそらくPythonライブラリを使うべきです:https://praw.readthedocs.io/en/latest/

登録しないと、直接REST reddit APIが彼らが持っている2秒間の1回の要求よりもさらに厳しい(?)。

0

dict()オブジェクトが要求されたとき(a = adict [key]の形式を使用)、PythonはKeyErrorを発生させ、そのキーは辞書にありません。

このエラーが発生したときのように、データ値が空です。

forループを実行する前に、辞書の長さを取得してみてください。空の場合、それは実行されません。ここで興味深いエラーチェックが役立つかもしれません。

size = len(risingData) 
if size: 
    for i in range(0,size): 
    … 
関連する問題