如何使用Tweepy API 2.0的StreamingClient从推文获取Twitter Handle
解决Tweepy StreamingClient获取Twitter Handle的问题
问题核心在于:Tweepy的StreamingClient基于Twitter API v2,默认的sample流不会返回用户的screen_name(API v2中改名为username)等信息,必须显式请求扩展字段并解析嵌套返回结构。
解决步骤
- 请求扩展字段:调用
sample()时指定expansions和tweet_fields参数,让API返回推文作者的关联用户数据。 - 匹配用户信息:API返回的JSON中,用户数据存放在
includes.users数组,需通过推文的author_id匹配对应用户,提取username。 - 保存与打印:将获取到的
username和推文数据整合后保存、打印。
修改后的完整代码
import json import time import tweepy KEY_FILE = './keys/bearer_token' DURATION = 10 def on_data(json_data): json_obj = json.loads(json_data.decode()) # 提取推文核心数据 tweet_id = json_obj.get('data', {}).get('id') tweet_text = json_obj.get('data', {}).get('text') author_id = json_obj.get('data', {}).get('author_id') # 匹配对应的用户username(即原screen_name) screen_name = None if 'includes' in json_obj and 'users' in json_obj['includes']: for user in json_obj['includes']['users']: if user['id'] == author_id: screen_name = user['username'] break # 终端打印结果 if screen_name: print(f'Tweet Screen Name: @{screen_name}') else: print(f'无法获取推文{tweet_id}的用户信息') # 构造待保存的数据结构 save_data = { 'tweet_id': tweet_id, 'tweet_text': tweet_text, 'screen_name': screen_name, 'raw_tweet_data': json_obj # 可选:保留原始完整数据 } # 写入JSON文件(每条数据单独一行,方便后续读取解析) with open('./collected_tweets/tweets.json', 'a', encoding='utf-8') as out: json.dump(save_data, out, ensure_ascii=False) out.write('\n') bearer_token = open(KEY_FILE).read().strip() streaming_client = tweepy.StreamingClient(bearer_token) # 调用采样流时指定扩展参数,获取作者关联数据 streaming_client.sample( threaded=True, expansions="author_id", tweet_fields="author_id" ) time.sleep(DURATION) streaming_client.disconnect()
关键细节说明
- API v2中,原
screen_name字段已更名为username,需提取user['username']。 expansions="author_id"指令让API返回与推文作者ID绑定的用户数据,存放在includes.users数组内。tweet_fields="author_id"确保推文数据中携带author_id,用于和用户数据做匹配关联。- 写入文件时添加
out.write('\n'),让每条JSON数据单独成行,避免后续读取时出现解析错误。
内容的提问来源于stack exchange,提问作者Roald Andre Kvarv
相关产品推荐
相关产品推荐

