Skip to main content
 首页 » 编程设计

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

2025年05月04日9unruledboy

我正在为大量用户收集推文,因此该脚本将在无人监督的情况下运行数天/数周。 我在 big_list 中有一个 user_id 列表。 我认为一些推文是私有(private)的,我的脚本停止了,所以我想要一种方法让脚本继续到下一个 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 

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

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

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

/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 block ?我不了解所有相关内容,因此不胜感激具有现场经验的人的最佳实践!

------------ 编辑 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 

请您参考如下方法:

你可以只做一个“pass”:

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