首页 > 解决方案 > 如何从用户 ID 获取推文?

问题描述

我有一个超过 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

非常感谢您的帮助!

标签: pythontweepy

解决方案


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

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

推荐阅读