在 tweepy 中使用推文 ID 检索推文列表

retrieving a list of tweets using tweet ID in tweepy

我有一个包含推文 ID 列表的文件,我想检索这些推文。该文件包含超过 100000 条推文,推特 API 只允许检索 100 条。

api = tweepy.API(auth)
good_tweet_ids = [i for i in por.TweetID[0:100]]
tweets = api.statuses_lookup(good_tweet_ids)
for tweet in tweets:
    print(tweet.text)

有没有办法检索更多的推文,比如 1000 或 2000,我不想对数据进行采样并将结果保存到文件中并每次都更改推文 ID 的索引,所以有吗一种方法!?

是的 - twitter 一次只允许您查找 100 条推文,但之后您可以立即查找另外 100 条推文。唯一需要注意的是速率限制——您受到每 15 分钟 window 可以拨打 API 的呼叫次数的限制。幸运的是,当您使用 wait_on_rate_limit=True 创建 API 时,tweepy 能够优雅地处理这个问题。然后,我们需要做的就是将完整的推文 ID 列表处理成 100 个或更少的批次(假设您有 130 个 - 第二批应该只是最后的 30 个)并一次查找一个。尝试以下操作:

import tweepy


def lookup_tweets(tweet_IDs, api):
    full_tweets = []
    tweet_count = len(tweet_IDs)
    try:
        for i in range((tweet_count / 100) + 1):
            # Catch the last group if it is less than 100 tweets
            end_loc = min((i + 1) * 100, tweet_count)
            full_tweets.extend(
                api.statuses_lookup(id=tweet_IDs[i * 100:end_loc])
            )
        return full_tweets
    except tweepy.TweepError:
        print 'Something went wrong, quitting...'

consumer_key = 'XXX'
consumer_secret = 'XXX'
access_token = 'XXX'
access_token_secret = 'XXX'

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, wait_on_rate_limit_notify=True)

# do whatever it is to get por.TweetID - the list of all IDs to look up

results = lookup_tweets(por.TweetID, api)

for tweet in results:
    if tweet:
        print tweet.text

对上述代码的补充。推文是推特状态对象时的输出格式。下面的一段代码会将其转换成可消毒的json,然后将其映射到tweet id以获得完整的df。

df = pd.read_csv('your.csv')
good_tweet_ids = [i for i in df.TweetID] #tweet ids to look up 
results = lookup_tweets(good_tweet_ids, api) #apply function

#Wrangle the data into one dataframe
import json
temp = json.dumps([status._json for status in results]) #create JSON
newdf = pd.read_json(temp, orient='records')
full = pd.merge(df, newdf, left_on='TweetID', right_on='id', how='left').drop('id', axis=1)