首页 > 解决方案 > 是否有更好/更快的方法来查询 twitter 以获取包含字符串的历史推文?

问题描述

因此,我试图获取自某年以来符合特定搜索条件的所有推文(目前我只是拉 X 条推文,看看这个数字是否能让我回到我感兴趣的那一年)。

搜索条件只是包含在推文中的字符串。以“苹果”为例。我也在尝试过滤掉 RT。

这显然将是数十万,可能更像是数百万条推文。

为了尝试实现这一点,我一直在使用 Tweepy Twitter API:

def getTweets(searchValue, numOfTweets):

    i = 0  
    tweetStream = tweepy.Cursor(twitterAPI.search, q=searchValue, tweet_mode="extended").items(numOfTweets)
    f = open('csvfile.csv','w')
    while True:
        try:
            for tweet in tweetStream:
                if (tweet.full_text[0:2] != 'RT'):
                    print('Tweets processed:' + str(i))
                    f.write(str(formatTweet(tweet.full_text)))
                    f.write(str(tweet.created_at) + '\n')
                    i += 1
            #Break here when all tweets in the stream have been processed
            break
        except tweepy.TweepError:
            print('Sleeping for 2 mins to maintain Twitter API connection... \n')
            time.sleep(120)
    f.close()

return True

问题是它运行得非常慢。每秒可能会发布 50 条推文。如果我需要返回几年,这意味着让我的程序运行数天/数周。

我以前没有使用过 Tweepy,所以我不确定实现我想要的最佳方式。我的代码是我在其他地方看到的几篇文章/答案的混搭,所以我确信我的方法可能存在几个问题。有什么建议么?

标签: pythonpython-3.xtwittertweepytwitterapi-python

解决方案


您可能想查看此文档developer.twitter.com


推荐阅读