python – 如何使用Twython返回100多个Twitter搜索结果?
发布时间:2020-12-20 13:39:34 所属栏目:Python 来源:网络整理
导读:在API上返回搜索结果时,Twitter每个“页面”只返回100条推文.它们在返回的search_metadata中提供max_id和since_id,可用作参数以获取更早/更晚的推文. Twython 3.1.2文档表明这种模式是搜索的“旧方法”: results = twitter.search(q="xbox",count=423,max_i
在API上返回搜索结果时,Twitter每个“页面”只返回100条推文.它们在返回的search_metadata中提供max_id和since_id,可用作参数以获取更早/更晚的推文.
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搜索大量推文的正确方法是什么,并迭代一组独特的结果? 编辑:这里的另一个问题是,当我尝试使用生成器进行迭代时(对于结果中的推文:),它会反复循环,而不会停止.啊 – 这是一个错误… https://github.com/ryanmcgrath/twython/issues/300 解决方法
我遇到了同样的问题,但似乎你应该使用max_id参数批量遍历用户的时间轴.根据Terence的答案,批次应该是100(但实际上,对于user_timeline 200是最大计数),并且只需将max_id设置为上一组返回的推文中的最后一个减去一(因为max_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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |