如何在Tweepy V2使用Paginator获取推文的preview_image_url
解决Tweepy V2 Paginator获取推文preview_image_url的问题
你遇到的核心问题是:使用Paginator.flatten()时,只会返回推文的基础数据(data部分),而通过expansions和media_fields请求到的媒体数据存储在响应的includes.media中,扁平化后无法关联这些扩展数据。
解决方案
不要直接使用flatten(),而是遍历Paginator返回的每个完整响应对象,将推文与对应的媒体数据关联:
client = tweepy.Client(bearer_token=my_keys.BEARER_TOKEN) username_list = ["coinfessions"] user_id = client.get_user(username="coinfessions").data.id print(user_id) # 遍历分页响应,保留完整的includes数据 for response in tweepy.Paginator( client.get_users_tweets, id=str(user_id), exclude=['retweets', 'replies'], expansions="attachments.media_keys", media_fields=["url", "preview_image_url"], max_results=5 ): # 构建media_key到媒体对象的映射,方便快速查找 media_map = {media.media_key: media for media in response.includes.get('media', [])} # 处理当前页的每条推文 for tweet in response.data: if tweet.attachments is not None: # 获取推文关联的所有media_key for media_key in tweet.attachments['media_keys']: # 通过映射找到对应的媒体对象 media = media_map.get(media_key) if media: # 访问preview_image_url等媒体字段 print(f"推文ID: {tweet.id}") print(f"预览图URL: {media.preview_image_url}") print(f"媒体URL: {media.url}\n")
关键说明
Paginator返回的每个response包含两部分核心数据:response.data是当前页的推文列表,response.includes是扩展请求到的关联数据(这里是媒体对象)- 用字典构建
media_map,可以通过推文里的media_key快速匹配到对应的媒体对象,从而获取preview_image_url等字段
内容的提问来源于stack exchange,提问作者Tarster
相关产品推荐
相关产品推荐

