使用Tweepy获取特定推文线程评论时遇AttributeError求助
解决Tweepy获取推文线程评论并保存的问题
错误原因
你碰到的AttributeError: 'Client' object has no attribute 'conversation'是因为Tweepy v2的Client类没有conversation这个方法,属于误用了不存在的接口。
修正方案
要获取指定推文线程的所有内容,需要用Tweepy v2的search_recent_tweets接口,结合conversation_id作为查询条件,同时要请求用户信息字段来获取推文作者名称。以下是修正后的代码:
import tweepy # 注意移除TOKEN前后的空格 BEARER_TOKEN = '你的Bearer Token' # 注意移除ID前后的空格 conversation_id = '目标推文的conversation_id' client = tweepy.Client(BEARER_TOKEN) # 构造查询条件,指定对话ID query = f"conversation_id:{conversation_id}" # 请求对话内推文,同时获取作者信息 response = client.search_recent_tweets( query=query, tweet_fields=['created_at'], user_fields=['name', 'username'], expansions='author_id', max_results=100 # 单次请求最多返回100条,内容更多需分页处理 ) # 将作者信息存入字典,方便通过author_id快速匹配 authors = {user.id: user for user in response.includes['users']} # 保存对话内容到TXT文件 with open(f"conversation_{conversation_id}.txt", "w", encoding='utf-8') as f: for tweet in response.data: author = authors[tweet.author_id] f.write(f"【{author.name} (@{author.username})】\n发布时间: {tweet.created_at}\n内容:\n{tweet.text}\n\n") print(f"对话已保存到conversation_{conversation_id}.txt")
分页补充(针对长对话)
如果对话线程的推文数量超过100条,需要通过分页获取全部内容,可使用Paginator实现:
from tweepy import Paginator all_tweets = [] authors = {} # 遍历分页结果,收集所有推文和作者信息 for response in Paginator(client.search_recent_tweets, query=query, tweet_fields=['created_at'], user_fields=['name', 'username'], expansions='author_id', max_results=100): all_tweets.extend(response.data) for user in response.includes['users']: if user.id not in authors: authors[user.id] = user # 保存逻辑不变,遍历all_tweets即可 with open(f"conversation_{conversation_id}.txt", "w", encoding='utf-8') as f: for tweet in all_tweets: author = authors[tweet.author_id] f.write(f"【{author.name} (@{author.username})】\n发布时间: {tweet.created_at}\n内容:\n{tweet.text}\n\n") print(f"完整对话已保存到conversation_{conversation_id}.txt")
内容的提问来源于stack exchange,提问作者Marc Genenger
相关产品推荐
相关产品推荐

