如何从用户ID获取推文?

时间:2020-10-12 18:25:42

标签: python tweepy

我有超过9000个用户ID的列表,我必须从每个用户中收集最多500条推文。我的代码运行了大约5天,仅收集了541个用户ID的推文。 我如何从所有帐户中获取推文?我的代码在做什么错了?

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

ids = df_all["id_str"].tolist()
api = tweepy.API(auth, wait_on_rate_limit=True) 


for id_ in ids:
    df = pd.DataFrame()
    
    outtweets = []
    
    try:
    
        for tweet in tweepy.Cursor(api.user_timeline,id=id_).items(500):

            outtweets.append({'id':id_,
                  'tw_id_str': tweet.id_str, 
                  'tw_created_at':tweet.created_at, 
                  'tw_favorite_count':tweet.favorite_count, 
                  'tw_retweet_count':tweet.retweet_count, 
                  'tw_text':tweet.text.encode("utf-8").decode("utf-8")})
        df = pd.DataFrame(outtweets)
        df.to_csv("tweets_of_ids.csv", mode='a')

    except tweepy.TweepError as e:
        continue

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

我实际上已经找到并改编了一些比上面的代码运行速度更快的代码行:

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)

outtweets=[] 

for id_ in ids:
    
    c = 0 
    
    try: 
        alltweets = [] 

        new_tweets = api.user_timeline(user_id = str(id_),count=200)

        #save most recent tweets
        alltweets.extend(new_tweets)

        #save the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1


        while len(new_tweets) > 0 and len(alltweets) <= 500:
            print(f"getting tweets before {oldest}")

            c = 500 - len(alltweets) 
            if c == 0: 
                break
            else:
                new_tweets = api.user_timeline(user_id = str(id_),count=c,max_id=oldest)
               
                alltweets.extend(new_tweets)

                oldest = alltweets[-1].id - 1

                print(f"...{len(alltweets)} tweets downloaded so far")

        for tweet in alltweets:
            outtweets.append({'id':id_, 'id_str':tweet.id_str, 'tw_created_at':tweet.created_at, 'tw_text':tweet.text})
    
    except tweepy.TweepError:
        print(id_)

    pass

答案 1 :(得分:0)

代码很好,但是Tweepy正在限制请求以避免超过速率限制(使用wait_on_rate_limit)。

api = tweepy.API(auth, wait_on_rate_limit=True) 

这种方法可以防止应用程序在超出限制时引发错误。

Premium APIs提供更高的利率。

相关问题