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

Tweepy V2调用search_all_tweets无法获取friends_count等属性报错

问题根源

你使用的是基于Twitter API v2的Tweepy V2版本,参考的属性说明是旧版Tweepy V1的规则,二者字段结构不兼容,因此访问friends_count、favorites_count属性时会抛出AttributeError。

字段对应说明
  • 你要找的friends_count就是V2返回结构中public_metrics下的following_count,二者含义完全一致,只是V2版本做了重命名,直接从public_metrics字典中取值即可。
  • favorites_count(用户累计点赞数)属于Twitter API v2未对外开放的字段,无论怎么调整user_fields请求参数都无法通过search_all_tweets这类公开接口获取,这是官方接口层面的限制,和Tweepy本身的代码实现无关。

你当前拿到的public_metrics仅返回4个字段是符合接口规则的,user.entities返回URL相关数据也是正常表现。

修正后的调用代码

Tweepy V2不会把扩展字段直接挂载为用户对象的顶层属性,需要从对应返回结构中读取,修改后的核心逻辑如下:

client = tweepy.Client(
    bearer_token=config.BEARER_TOKEN,
    consumer_key=config.CONSUMER_KEY,
    consumer_secret=config.CONSUMER_SECRET,
    access_token=config.ACCESS_TOKEN,
    access_token_secret=config.ACCESS_TOKEN_SECRET
)

for response in tweepy.Paginator(
    client.search_all_tweets,
    query=s,
    tweet_fields=['context_annotations', 'created_at', 'public_metrics', 'author_id', 'lang', 'geo', 'entities'],
    user_fields=['username', 'entities', 'public_metrics', 'location', 'verified', 'description'],
    max_results=100,
    expansions='author_id'
):
    for user in response.includes["users"]:
        print(user.public_metrics)
        print(user.entities)
        # 获取原V1版本的friends_count数值
        friends_count = user.public_metrics['following_count']
        print(friends_count)
        # favorites_count无公开返回通道,无法通过该接口获取
        print("当前公开接口不支持返回favorites_count字段")

提示:Twitter API v2采用字段声明式返回规则,只有你在请求参数中明确列出、且官方对该接口开放的字段,才会出现在最终返回结果中,未开放的字段即使写入请求参数也不会返回。

内容的提问来源于stack exchange,提问作者Stephen Wong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:25:34