使用Tweepy获取推文时entities字段为空,如何提取外部链接?
解决Twitter API获取推文entities为空的问题
- 先确认测试用的推文本身是否包含外部链接:如果目标用户的这条推文根本没加链接,那
entities字段自然是空的,找一条明确带外链的推文测试更准确。 - 别混淆
attachments和entities的作用:attachments是存图片、视频、投票这类内容的,外部链接确实在entities的urls数组里,但如果链接是在被引用的推文中(比如转发的推文里的链接),你当前的请求拿不到这些内容。 - 扩展请求参数获取完整内容:如果要抓转发/引用推文中的链接,需要加上
expansions参数,同时补充tweet_fields,调整后的代码示例:
author_id = 12345 # 加上expansions获取引用推文,同时保留entities字段 response = Client.get_users_tweets( author_id, tweet_fields=['entities', 'referenced_tweets'], expansions='referenced_tweets.id', max_results=100 # 可选,获取更多推文提高命中带链接的概率 ) # 遍历返回的原始推文 for tweet in response.data: if hasattr(tweet, 'entities') and 'urls' in tweet.entities: print([url['expanded_url'] for url in tweet.entities['urls']]) else: print("该推文无外部链接") # 遍历引用的推文(如果有) if hasattr(response, 'includes') and 'tweets' in response.includes: for ref_tweet in response.includes['tweets']: if hasattr(ref_tweet, 'entities') and 'urls' in ref_tweet.entities: print([url['expanded_url'] for url in ref_tweet.entities['urls']])
- 检查API权限:免费版的Twitter API可能限制部分字段访问,确认你的开发者账号权限等级足够获取
entities字段。
内容的提问来源于stack exchange,提问作者S. Neri
相关产品推荐
相关产品推荐

