在Tweepy中优雅地处理user_timeline方法的错误和异常

cd9*_*d98 1 python twitter tweepy

我正在为大量用户收集推文,因此该脚本将在无人监督的情况下运行数天/数周.我有一个user_ids列表big_list.我认为有些推文是私有的,我的脚本会停止,所以我想让脚本继续使用下一个user_id(并且可能会打印一条警告消息).

我还想了解如何使其对其他错误或异常具有鲁棒性(例如,脚本在出错或超时时休眠)

这是我的总结:

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
Run Code Online (Sandbox Code Playgroud)

get_all_tweets函数抛出错误,它基本上反复调用:

my_api.user_timeline(user_id = id_str, count=200)
Run Code Online (Sandbox Code Playgroud)

以防万一,它给出的回溯如下:

/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.
Run Code Online (Sandbox Code Playgroud)

如果您需要更多详细信息,请告诉我们.谢谢!

-----------编辑--------

这个问题有一些信息.

我想我可以尝试try/except为不同类型的错误做一个块?我不知道所有相关的,所以有现场经验的人的最佳实践将不胜感激!

----------编辑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
Run Code Online (Sandbox Code Playgroud)

小智 5

你可以做一个"通行证":

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
Run Code Online (Sandbox Code Playgroud)


小智 5

我真的很迟,但在这些日子里我遇到了同样的问题.因为需要time.sleep()我解决了这个问题,这要归功于alecxe对这个问题的回复.

我过去潜水,但我希望这将有助于将来的某些人.