2014-12-08 52 views
1

我正在收集大量用戶的推文,因此該腳本將在無監督的情況下運行數天/周。 我有一個user_id列表big_list。 我認爲有些推文是私人的,我的腳本停下來,所以我想讓腳本繼續下一個user_id(也許會打印一條警告消息)。在Tweepy中優雅地處理user_timeline方法的錯誤和例外

我也會喜歡上如何使其健壯到其他錯誤或異常(例如,用於腳本在錯誤或超時睡眠)

這是什麼,我有一個總結建議:

import tweepy 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_token_secret) 
my_api = tweepy.API(auth) 

for id_str in big_list: 
    all_tweets = get_all_tweets(id_str=id_str, api=my_api) 
    #Here: insert some tweets into my database 

get_all_tweets函數拋出的錯誤,它基本上重複調用:

my_api.user_timeline(user_id = id_str, count=200) 

以防萬一,它給人的回溯是後續ing:

/home/username/anaconda/lib/python2.7/site-packages/tweepy/binder.pyc in execute(self) 
    201     except Exception: 
    202      error_msg = "Twitter error response: status code = %s" % resp.status 
--> 203     raise TweepError(error_msg, resp) 
    204 
    205    # Parse the response payload 

TweepError: Not authorized. 

讓我知道你是否需要更多的細節。謝謝!

-----------編輯--------

This question有一些信息。

我想我可以嘗試做一個try/except塊爲不同類型的錯誤?我不知道所有相關的,所以有經驗的人的最佳實踐將不勝感激!

---------- EDIT 2 -------

我得到一些Rate limit exceeded errors所以我做了循環睡眠這樣。 else部分將處理「未經授權」錯誤和一些其他(未知?)錯誤。儘管如此,這仍然讓我失去了big_list中的元素。

for id_str in big_list: 
    try: 
     all_tweets = get_all_tweets(id_str=id_str, api=my_api) 
     # HERE: save tweets 
    except tweepy.TweepError, e: 
     if e == "[{u'message': u'Rate limit exceeded', u'code': 88}]": 
      time.sleep(60*5) #Sleep for 5 minutes 
     else: 
      print e 

回答

4

你可能只是做了一個「通」:

import tweepy 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_token_secret) 
my_api = tweepy.API(auth) 

for id_str in big_list: 
    try: 
     all_tweets = get_all_tweets(id_str=id_str, api=my_api) 
    except Exception, e: 
     pass 
+0

感謝您的回答。您的解決方案有效,但我也在尋找處理其他相關例外的方法。我編輯了我的問題以添加其中的一個(超出速率限制)。對於「未經授權」我可以繼續循環,但爲了超過速率限制,我需要''time.sleep()',否則我會一直被拒絕。 – cd98 2014-12-08 16:34:54

+0

這應該適用於不同類型的例外情況 http://stackoverflow.com/a/17168626/2838313 當您得到率異常時,您可能會睡眠所需的時間! (同時保存循環的當前狀態) – abad 2014-12-08 16:41:00

5

我真的很晚,但我在這些日子裏所面臨的同樣的問題。爲了time.sleep()的需要,我通過alecxe reply to this question解決了這個問題。

我在過去潛水,但我希望這將有助於未來的人。