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

如何使用Tweepy通过Twitter账号ID获取用户名

使用Tweepy通过Twitter ID获取用户名的详细步骤

一、前期准备

  • 注册Twitter开发者账号,创建Project后获取以下4个密钥:
    • API Key
    • API Secret Key
    • Access Token
    • Access Token Secret
  • 安装Tweepy:打开终端/命令提示符,执行pip install tweepy

二、读取本地JSON文件

假设你的JSON文件结构类似(如果结构不同,调整代码里的读取逻辑即可):

{
  "twitter_ids": [123456789, 987654321, 1122334455]
}

用Python读取JSON的代码:

import json

# 替换成你的JSON文件路径
with open("your_twitter_ids.json", "r", encoding="utf-8") as f:
    data = json.load(f)
# 提取ID列表,这里假设键是"twitter_ids",根据你的实际结构修改
user_ids = data["twitter_ids"]

三、配置Tweepy并批量获取用户名

Twitter API允许一次最多查询100个ID,所以我们把ID列表分批处理,避免触发限制:

import tweepy

# 填入你从开发者平台获取的密钥
API_KEY = "你的API Key"
API_SECRET = "你的API Secret Key"
ACCESS_TOKEN = "你的Access Token"
ACCESS_TOKEN_SECRET = "你的Access Token Secret"

# 完成认证
auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

# 创建API对象,开启自动等待速率限制
api = tweepy.API(auth, wait_on_rate_limit=True)

# 分批处理ID,每批100个
batch_size = 100
id_to_username = {}

for i in range(0, len(user_ids), batch_size):
    batch = user_ids[i:i+batch_size]
    try:
        # 批量查询用户信息
        users = api.lookup_user(user_ids=batch)
        for user in users:
            # 存储ID和对应的@用户名(screen_name即为用户名)
            id_to_username[str(user.id)] = user.screen_name
    except tweepy.TweepError as e:
        print(f"处理批次时出错: {e}")

# 打印结果示例
for user_id, username in id_to_username.items():
    print(f"ID: {user_id} -> @{username}")

四、保存结果(可选)

把ID和用户名的对应关系保存为新JSON文件:

with open("id_to_username.json", "w", encoding="utf-8") as f:
    json.dump(id_to_username, f, ensure_ascii=False, indent=4)

注意事项

  • 如果JSON里的ID是字符串类型,无需转换,Tweepy会自动处理
  • 确保开发者账号权限足够,部分权限可能需要额外申请
  • 若遇到账号已删除/封禁的ID,API会自动跳过这类ID,不会返回结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:40:35