如何用Twython返回超过100个Twitter搜索结果?

2024-05-13 04:47:13 发布

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

Twitter在API上返回搜索结果时,每个“页面”只返回100条tweets。它们在返回的search_metadata中提供max_idsince_id,可以用作获取早期/后期tweets的参数。

Twython 3.1.2文档表明,这种模式是搜索的“老方法”:

results = twitter.search(q="xbox",count=423,max_id=421482533256044543)
for tweet in results['statuses']:
    ... do something

这就是“new way”:

results = twitter.cursor(t.search,q='xbox',count=375)
for tweet in results:
    ... do something

当我执行后者时,它似乎会无休止地重复相同的搜索结果。我试着把它们推到CSV文件中,但它会推送大量的副本。

使用Twython搜索大量tweets并遍历一组唯一结果的正确方法是什么?

编辑:这里的另一个问题是,当我尝试使用生成器(for tweet in results:)迭代时,它会重复循环,而不会停止。啊——这是只虫子。。。https://github.com/ryanmcgrath/twython/issues/300


Tags: 方法inidforsearchcounttwitterdo
3条回答

我也遇到了同样的问题,但似乎应该使用max_id参数成批循环遍历用户的时间线。根据Terence的答案,批处理应该是100(但实际上,对于用户而言,时间线200是最大计数),只需将最大id设置为前一组返回tweets中的最后一个id减去1(因为最大id是包含的)。代码如下:

'''
Get all tweets from a given user.
Batch size of 200 is the max for user_timeline.
'''
from twython import Twython, TwythonError
tweets = []
# Requires Authentication as of Twitter API v1.1
twitter = Twython(PUT YOUR TWITTER KEYS HERE!)
try:
    user_timeline = twitter.get_user_timeline(screen_name='eugenebann',count=200)
except TwythonError as e:
    print e
print len(user_timeline)
for tweet in user_timeline:
    # Add whatever you want from the tweet, here we just add the text
    tweets.append(tweet['text'])
# Count could be less than 200, see:
# https://dev.twitter.com/discussions/7513
while len(user_timeline) != 0: 
    try:
        user_timeline = twitter.get_user_timeline(screen_name='eugenebann',count=200,max_id=user_timeline[len(user_timeline)-1]['id']-1)
    except TwythonError as e:
        print e
    print len(user_timeline)
    for tweet in user_timeline:
        # Add whatever you want from the tweet, here we just add the text
        tweets.append(tweet['text'])
# Number of tweets the user has made
print len(tweets)

您需要重复调用python方法。然而,不能保证这些是下一个N,或者如果tweets真的进来了,它可能会错过一些。

如果您希望所有tweets都在一个时间范围内,那么可以使用流api:https://dev.twitter.com/docs/streaming-apis,并将其与oauth2模块结合起来。

How can I consume tweets from Twitter's streaming api and store them in mongodb

python-twitter streaming api support/example

免责声明:我实际上没有试过

根据official Twitter API documentation

Count optional

The number of tweets to return per page, up to a maximum of 100

相关问题 更多 >