2017-07-06 41 views
0

下面是我使用爲目的。對於它的時間太長的時間來下載所有tweets.What每個用戶請求的代碼有一些方法,以加快執行time.The想法是實時的使用鳴叫分析作爲用戶訪問該網站。我是新的python,所以任何幫助,將不勝感激。有沒有什麼辦法來加速python代碼使用tweepy下載tweets?

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 

回答

2

讓您的解決方案更快的一種方法是製作一些緩存。

當你下載了所有微博的網名,保存在本地,例如爲[twitter_screen_name]以.json

然後編輯功能來檢查你的緩存文件。如果它不存在,請將其創建爲空。然後加載它,只刷新需要的內容,並保存你的json緩存文件。

這樣,當用戶訪問時,您將只下載使用twitter的diff。對於定期諮詢的屏幕名稱,這將更快。

然後,你可以添加一些自動清除緩存 - 一個簡單的CRON,與去年訪問的META於n天例如舊的刪除文件。

相關問題