0

我的代码试图在 2014 年 10 月 1 日收集有关“汽车”的推文。为了尝试处理速率限制或任何其他与 Twitter 相关的错误(即容量过剩),我在最后实现了代码,告诉程序在发生 TweepError 时停止并等待 20 分钟。

不幸的是,它不起作用,因为脚本崩溃了,我仍然可以看到速率限制错误消息。请指教,谢谢。

import tweepy
import time
import csv

ckey = "xxx"
csecret = "xxx"
atoken = "xxx-xxx"
asecret = "xxx"

OAUTH_KEYS = {'consumer_key':ckey, 'consumer_secret':csecret,
    'access_token_key':atoken, 'access_token_secret':asecret}
auth = tweepy.OAuthHandler(OAUTH_KEYS['consumer_key'], OAUTH_KEYS['consumer_secret'])
api = tweepy.API(auth)

startSince = '2014-10-01'
endUntil = '2014-10-02'

searchTerms = 'cars'

for tweet in tweepy.Cursor(api.search, q=searchTerms, 
    since=startSince, until=endUntil).items(999999999):

    try:
        print "Name:", tweet.author.name.encode('utf8')
        print "Screen-name:", tweet.author.screen_name.encode('utf8')
        print "Tweet created:", tweet.created_at

    except tweepy.error.TweepError:
        time.sleep(60*20)
        continue

    except tweepy.TweepError:
        time.sleep(60*20)
        continue

    except TweepError:
        time.sleep(60*20)
        continue

    except IOError:
        time.sleep(60*5)
        continue

    except StopIteration:
        break
4

1 回答 1

1

Your issue is that your try-except statement happens independent of your call to the Twitter API. The tweepy.Cursor is what triggers the rate-limit error. Try including this line:

for tweet in tweepy.Cursor(api.search, q=searchTerms, 
    since=startSince, until=endUntil).items(999999999):

within your try and see if the TweepError is caught (it should be). You may need a small modification to get the cursor to continue from the proper location but it should be trivial.

于 2014-10-14T20:05:03.703 回答