Tweepy(Twitter API)不返回所有搜索结果

2024-05-17 14:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Twitter上使用Tweepy的搜索功能,由于某些原因,搜索结果限制在15个。这是我的密码

results=api.search(q="Football",rpp=1000)

for result in results:
    print "%s" %(clNormalizeString(result.text))

print len(results)

只返回15个结果。这和不同页面的结果有什么关系吗?


Tags: in功能api密码forsearch原因twitter
2条回答

问题更多的是关于Twitter API而不是tweepy本身。

根据documentationcount参数定义:

The number of tweets to return per page, up to a maximum of 100. Defaults to 15. This was formerly the "rpp" parameter in the old Search API.

仅供参考,您可以使用tweepy.Cursor获取分页结果,如下所示:

import tweepy


auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)

api = tweepy.API(auth)
for tweet in tweepy.Cursor(api.search,
                           q="google",
                           count=100,
                           result_type="recent",
                           include_entities=True,
                           lang="en").items():
    print tweet.created_at, tweet.text

另请参见:https://github.com/tweepy/tweepy/issues/197

希望能有所帮助。

下面是一个最小的工作示例(一旦你用真正的密钥替换假密钥)。

import tweepy
from math import ceil

def get_authorization():

    info = {"consumer_key": "A7055154EEFAKE31BD4E4F3B01F679",
            "consumer_secret": "C8578274816FAEBEB3B5054447B6046F34B41F52",
            "access_token": "15225728-3TtzidHIj6HCLBsaKX7fNpuEUGWHHmQJGeF",
            "access_secret": "61E3D5BD2E1341FFD235DF58B9E2FC2C22BADAD0"}

    auth = tweepy.OAuthHandler(info['consumer_key'], info['consumer_secret'])
    auth.set_access_token(info['access_token'], info['access_secret'])
    return auth


def get_tweets(query, n):
    _max_queries = 100  # arbitrarily chosen value
    api = tweepy.API(get_authorization())

    tweets = tweet_batch = api.search(q=query, count=n)
    ct = 1
    while len(tweets) < n and ct < _max_queries:
        print(len(tweets))
        tweet_batch = api.search(q=query, 
                                 count=n - len(tweets),
                                 max_id=tweet_batch.max_id)
        tweets.extend(tweet_batch)
        ct += 1
    return tweets

注意:我确实尝试过使用for循环,但是twitter api有时返回的结果少于100个(尽管有人要求100个,并且有100个可用)。我不知道这是为什么,但这就是为什么我没有包括一个检查,以打破循环,如果tweet_批是空的-你可能想自己添加这样的检查,因为有一个query rate limit

另一个注意事项:可以通过调用wait_on_rate_limit=True来避免达到速率限制

        api = tweepy.API(get_authorization(), wait_on_rate_limit=True)

相关问题 更多 >