我正在为大量用户收集推文,因此该脚本将在无人监督的情况下运行数天/数周。
我在big_list
中有一个user_id列表。
我认为有些推文是私有的,我的脚本停止了,所以我想让脚本继续使用下一个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
阻止?我不知道所有相关的内容,所以有实地经验的人的最佳实践将不胜感激!
----------编辑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
答案 0 :(得分: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
答案 1 :(得分:5)
我的确很晚,但在这些日子里我遇到了同样的问题。由于需要time.sleep(),我感谢alecxe reply to this question解决了这个问题。
我过去潜水,但我希望这将有助于将来。
答案 2 :(得分:0)
在创建API对象并添加常规的tweepy错误处理时,您可以仅使用Tweepy的“ wait_on_ratelimit”和“ wait_on_rate_limit_notify”,然后在显示特定错误的情况下,您可以尝试个性化处理每个错误的代码。应该是这样的:
import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
my_api = tweepy.API(auth, wait_on_rate_limit = True, wait_on_rate_limit_notify = True)
for id_str in big_list:
try:
all_tweets = get_all_tweets(id_str=id_str, api=my_api)
except tweepy.TweepError as e:
print("Tweepy Error: {}".format(e))