【问题标题】:Tweepy api limit workaroundTweepy api 限制解决方法
【发布时间】:2016-09-03 01:43:43
【问题描述】:

我正在尝试下载芝加哥地区的一些 Twitter 数据,特别关注与犯罪相关的推文。我还需要用坐标对这些进行地理标记。我想获得大量用于分析目的,但是 REST API 是有限的,因此将其限制在一个相当低的数字。基于类似的问题Avoid twitter api limitation with Tweepy,我一直在尝试解决此问题,但是到目前为止,我运气不佳。谁能帮我解决这个问题?我是所有这类东西的新手,所以任何帮助都会非常感激。理想情况下,我也希望在 pandas 数据框中也能做到这一点。我一直在使用以下教程作为编码的基础。这可以在以下位置找到: http://www.karambelkar.info/2015/01/how-to-use-twitters-search-rest-api-most-effectively./ 我已经复制了下面的代码:

import tweepy
auth = tweepy.AppAuthHandler('', '')
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
if (not api):
print ("Can't Authenticate")
sys.exit(-1)

import sys
import jsonpickle
import os



searchQuery = 'shooting OR stabbing OR violence OR assualt OR attack OR homicide OR punched OR mugging OR murder'
geocode= "41.8781,-87.6298,15km"


maxTweets = 1000000
tweetsPerQry = 100
fName = 'tweets.txt'
sinceId = None
max_id = 1L
tweetCount = 0
print ("Downloading max {0} tweets".format(maxTweets))
with open (fName, 'w') as f:
  while tweetCount < maxTweets:
    try:
        if (max_id <= 0):
            if(not sinceId):
                new_tweets = api.search(q=searchQuery, geocode=geocode, count=tweetsPerQry)
            else:
                new_tweets = api.search(q=searchQuery, geocode=geocode, count=tweetsPerQry, since_id=sinceID)
        else:
            if (not sinceId):
                new_tweets = api.search(q=searchQuery, geocode=geocode, count=tweetsPerQry, max_id=str(max_id-1))
            else:
                new_tweets = api.search(q=searchQuery, geocode=geocode, count=tweetsPerQry, max_id=str(max_id-1), since_id=sinceId)
        if not new_tweets:
            print ("No more tweets found")
            break
        for tweet in new_tweets:
            f.write(jsonpickle.encode(tweet._json, unpicklable=False)+'\n')
        tweetCount += len(new_tweets)
        print("Downloaded {0} tweets".format(tweetCount))
        max_id = new_tweets[-1].id
    except tweepy.TweepError as e:
        print("some error : " + str(e))
        break
print ("Downloaded {0} tweets, Saved to {1}".format(tweetCount, fName))

【问题讨论】:

  • 在这种情况下,“运气不佳”究竟是什么意思?错误?意外行为?请给minimal reproducible example (并尽量不要在未来分享您的 API 令牌)。
  • 感谢您这么快回复!抱歉,这是我的疏忽。谢谢你删除这个。就运气不佳而言,它似乎只是挂起,好像它正在处理一样,但是当我检查我的文本文件时,里面什么都没有,而我希望它在运行一段时间后至少有一些数据.
  • 我没有收到任何错误信息,只是为了澄清
  • 另外这可能会有所帮助,我一直在使用以下教程作为此代码的基础:

标签: python api twitter limit tweepy


【解决方案1】:

在遇到同样的问题后,我创建了一种识别即将发生的 API 速率限制的方法。此 python 代码使用 tweepy,它将打印发出的 API 请求数和剩余的允许请求数。您可以在达到限制之前或之后添加自己的代码来延迟/睡眠/等待,或者使用 tweepy wait_on_rate_limit(更多详细信息HERE)。

示例输出:

Twitter API:使用 3 个请求,剩余 177 个,用于对 /search/tweets 的 API 查询

Twitter API:使用 3 个请求,剩余 177 个,用于对 /application/rate_limit_status 的 API 查询

api = tweepy.API(auth)


#Twitter's words on API limits https://support.twitter.com/articles/15364

#### Define twitter rate determining loop
def twitter_rates():
    stats = api.rate_limit_status()  #stats['resources'].keys()
    for akey in stats['resources'].keys():
        if type(stats['resources'][akey]) == dict:
            for anotherkey in stats['resources'][akey].keys():
                if type(stats['resources'][akey][anotherkey]) == dict:
                    #print(akey, anotherkey, stats['resources'][akey][anotherkey])
                    limit = (stats['resources'][akey][anotherkey]['limit'])
                    remaining = (stats['resources'][akey][anotherkey]['remaining'])
                    used = limit - remaining
                    if used != 0:
                        print("Twitter API used", used, "remaining queries", remaining,"for query type", anotherkey)
                    else:
                        pass
                else:
                    pass  #print("Passing")  #stats['resources'][akey]
        else:
            print(akey, stats['resources'][akey])
            print(stats['resources'][akey].keys())
            limit = (stats['resources'][akey]['limit'])
            remaining = (stats['resources'][akey]['remaining'])
            used = limit - remaining
            if used != 0:
                print("Twitter API:", used, "requests used,", remaining, "remaining, for API queries to", akey)
                pass


twitter_rates()

另请注意,wait_on_rate_limit将停止异常。Tweepy 将休眠,但需要多长时间才能补充速率限制。” Aaron Hill 2014 年 7 月,@987654322 @ 是一个 Stackoverflow 页面,上面有更多的 cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2019-06-02
    • 1970-01-01
    相关资源
    最近更新 更多