【问题标题】:Is there any way to speed-up python code for downloading tweets using tweepy?有什么方法可以加速使用 tweepy 下载推文的 python 代码?
【发布时间】:2017-07-06 11:14:43
【问题描述】:

这是我为此目的使用的代码。对于每个用户请求,下载所有推文都需要很长时间。有哪些方法可以加快执行时间。想法是实际使用推文分析用户访问网站的时间。我是 python 新手,所以任何帮助将不胜感激。

import tweepy #https://github.com/tweepy/tweepy


#Twitter API credentials
consumer_key = ".."
consumer_secret = ".."
access_key = ".."
access_secret = ".."


def get_all_tweets(screen_name):
    #Twitter only allows access to a users most recent 3240 tweets with this method

    #authorize twitter, initialize tweepy
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    #initialize a list to hold all the tweepy Tweets
    alltweets = []  

    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.user_timeline(screen_name = screen_name,count=200)

    #save most recent tweets
    alltweets.extend(new_tweets)

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

    #keep grabbing tweets until there are no tweets left to grab
    while len(new_tweets) > 0:
        print ("getting tweets before %s".format(oldest))

        #all subsiquent requests use the max_id param to prevent duplicates
        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)

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

        print ("...%s tweets downloaded so far".format(len(alltweets)))

    #transform the tweepy tweets into a 2D array that will populate the csv 
    outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
    return outtweets

【问题讨论】:

    标签: python python-3.x twitter tweepy


    【解决方案1】:

    使您的解决方案更快的一种方法是制作一些缓存。

    当您下载了一个屏幕名称的所有推文后,将它们保存在本地,例如 [twitter_screen_name].json

    然后编辑您的函数以检查您的缓存文件。如果它不存在,则将其创建为空。然后加载它,只刷新需要的内容,然后保存你的 json 缓存文件。

    这样,当用户访问时,您将只下载带有 twitter 的 diff。对于经常查阅的网名,这会快得多。

    然后,您可以添加一些东西来自动清除缓存 - 例如,一个简单的 CRON 可以删除上次访问的 META 超过 n 天的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2018-10-30
      相关资源
      最近更新 更多