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

如何使用Tweepy Paginator获取Twitter用户名与全名?

解决方法

你的问题出在expansions参数的选择和用户数据的获取逻辑上,调整如下:

  1. 要获取推文作者的用户信息,需将expansions设为author_id——你之前用的entities.mentions.username是用来获取推文中提及的用户,而非推文发布者。
  2. Twitter API返回的用户数据会存放在响应的includes['users']集合里,不会直接绑定在tweet对象上,需要通过推文的author_id匹配对应的用户信息。

修改后的完整代码:

query="covid-is:retweet"
for page in tweepy.Paginator(client.search_recent_tweets, 
                          query=query, 
                          expansions='author_id',  # 改为关联推文作者ID
                          user_fields=['username', 'name', 'location'],  # 按需添加用户字段,比如全名、地点
                          tweet_fields=['context_annotations', 'created_at'], 
                          max_results=10):
    # 将用户列表转为字典,用用户ID作为键,方便快速匹配
    user_map = {user.id: user for user in page.includes.get('users', [])}
    # 遍历当前页的推文
    for tweet in page.data:
        print(f"推文ID: {tweet.id}")
        # 通过推文的author_id获取对应的用户对象
        target_user = user_map.get(tweet.author_id)
        if target_user:
            print(f"用户名(@后内容): {target_user.username}")
            print(f"用户全名: {target_user.name}")
            print(f"用户填写的地点: {target_user.location}\n")

额外说明

如果你的需求是获取推文中被提及的用户(而非推文作者),才需要保留expansions='entities.mentions.username',此时可以通过tweet.entities['mentions']里的用户名去includes['users']中匹配对应的用户数据。

内容的提问来源于stack exchange,提问作者M A Nezam Sagor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:20:41