You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Tweepy与Twitter API v2获取单条推文全部回复失败求助

问题分析与解决

核心问题

你的代码犯了一个典型错误——循环里每次迭代都用新批次的推文和用户数据覆盖了之前的变量,最后只保留了最后一页的结果,这就是为什么只能拿到寥寥几条回复的原因。另外,加.flatten(limit=1000)报错,大概率是因为这个方法只处理推文数据,没法同步处理关联的用户信息,导致后续查找用户时出错。

修正后的代码

import csv
import tweepy
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

# 认证与客户端创建
bearer_token = "XXX"
client = tweepy.Client(bearer_token)

# 替换为目标推文的conversation_id
q = 'conversation_id:XXX'

# 初始化空列表存储所有推文和用户数据
all_tweets = []
all_users = []

# 使用Paginator遍历所有分页结果
for tweet_batch in tweepy.Paginator(client.search_recent_tweets, 
                                    query=q,
                                    tweet_fields=['context_annotations','created_at', 'public_metrics', 'author_id'], 
                                    user_fields=['name','username','location','verified','description'],
                                    max_results=100, 
                                    expansions='author_id'):
    # 将当前页的推文添加到总列表
    if tweet_batch.data:
        all_tweets.extend(tweet_batch.data)
    # 将当前页的用户数据添加到总列表
    if "users" in tweet_batch.includes:
        all_users.extend(tweet_batch.includes["users"])

# 转换用户数据为字典,方便通过author_id查找
user_dict = {user.id: user for user in all_users}
print(f"共获取到 {len(all_tweets)} 条回复,{len(user_dict)} 个用户")

# 写入CSV文件
with open('replies_clean.csv', 'w', encoding='utf-8') as f:
    csv_writer = csv.DictWriter(f, fieldnames=('user', 'text'))
    csv_writer.writeheader()
    for tweet in all_tweets:
        user = user_dict[tweet.author_id]
        row = {
            'user': '@' + user.username,
            'text': tweet.text.replace('\n', ' ')
        }
        csv_writer.writerow(row)

额外注意事项

  • 时间范围限制:search_recent_tweets只能获取最近7天的推文,如果目标推文的回复有超过7天的,这个接口根本拿不到,得用需要学术研究权限的search_all_tweets接口。
  • API调用限制:推特API有速率限制,Paginator会自动处理分页,但不要短时间内频繁调用,避免触发限流。
  • flatten方法误区:flatten只提取推文数据,会丢失关联的用户信息,不适合需要同步获取用户数据的场景,手动遍历分页更稳妥。

内容的提问来源于stack exchange,提问作者James Billings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:06:33