使用Twython提取推文

0 投票
2 回答
2485 浏览
提问于 2025-04-17 22:38

我正在使用Twython这个Twitter API来提取推文。但是我只得到了100条推文。我想提取从2013年12月10日到2014年3月10日之间的推文。我在搜索功能中设置了count=1000。

我明白速率限制是100条。那么有没有办法在这个时间段内获取那些推文,而不受速率限制呢?

 from twython import Twython
 import csv
 from dateutil import parser
 from dateutil.parser import parse as parse_date
 import datetime
 from datetime import datetime
 import pytz

 utc=pytz.UTC

 APP_KEY = 'xxxxxxxxxxx'    
 APP_SECRET = 'xxxxxxxxxxx'
 OAUTH_TOKEN = 'xxxxxxxx'  # Access Token here
 OAUTH_TOKEN_SECRET = 'xxxxxxxxxxx'  

 t = Twython(app_key=APP_KEY, app_secret=APP_SECRET, oauth_token=OAUTH_TOKEN,      oauth_token_secret=OAUTH_TOKEN_SECRET)

 search=t.search(q='AAPL', count="1000",since='2013-12-10')
 tweets= search['statuses']


 for tweet in tweets:
     do something

2 个回答

1

使用Twython的时候,搜索的功能有点限制,但我用get_user_timeline这个方法取得了一些成功。

我之前遇到过类似的问题,想要获取某个用户最近的X条推文。

如果你查看一下文档,你会发现我用的一个小技巧是:记录下我最后读到的那条推文的ID,然后在下次请求的时候,用max_id参数来读取直到那条推文为止。

对于你的情况,你只需要修改一下while循环,让它在某个条件下停止,比如根据'created_at'的时间。像这样可能就能实现:

# Grab the first 200 tweets
last_id = 0
full_timeline = 200
result = t.get_user_timeline(screen_name='NAME', count = full_timeline)

for tweet in result:
    print(tweet['text'], tweet['created_at'])
    last_id = tweet['id']

# Update full timeline to see how many tweets were actually received
# Full timeline will be less than 200 if we read all the users tweets
full_timeline = len(result)

# 199 cause result[1:] is used to trim duplicated results cause of max_id
while full_timeline >= 199:
    result = t.get_user_timeline(screen_name='NAME', count = 200, max_id = last_id)

    # Since max_id is inclusive with its bound, it will repeat the same tweet we last read, so trim out that tweet
    result = result[1:]
    for tweet in result:
        print(tweet['text'], tweet['created_at'])
        last_id = tweet['id']

    # Update full_timeline to keep loop going if there are leftover teweets
    full_timeline = len(result)
3

在通过 Search API 访问推文时,有一些限制。你可以查看这个 文档

通常情况下, Search API 只能提供过去一周的推文。

所以你想要获取过去3到4个月的推文,但你找不到那些旧的推文。

撰写回答