gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:53:04 25 4
gpt4 key购买 nike

Twitter 在 API 上返回搜索结果时,每个“页面”仅返回 100 条推文。他们在返回的 search_metadata 中提供了 max_idsince_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 搜索大量推文并循环访问唯一结果集的正确方法是什么?

编辑:这里的另一个问题是,当我尝试使用生成器进行迭代时(for tweet in results:),它不断循环,没有停止。啊——这是一个错误... https://github.com/ryanmcgrath/twython/issues/300

最佳答案

我遇到了同样的问题,但似乎您应该使用 max_id 参数分批循环遍历用户的时间线。根据 Terence 的回答,批处理应为 100(但实际上,对于 user_timeline,200 是最大计数),只需将 max_id 设置为前一组返回的推文中的最后一个 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)

关于python - 如何使用 Twython 返回超过 100 个 Twitter 搜索结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21043674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com