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

2023年2月9日后,能否用免费版Twitter API v2获取指定账号粉丝数?

问题:2023年2月9日后,免费版Twitter API v2能否获取指定账号粉丝数

我尝试用以下代码调用API获取指定账号粉丝数,但出现403 Forbidden错误,想知道2023年2月9日之后还能不能用免费版Twitter API v2做这件事?

原代码

import tweepy
import requests

# Replace with your own keys and tokens

API_KEY = 'persnal key'
API_SECRET_KEY = 'persnal key'
ACCESS_TOKEN = 'persnal key'
ACCESS_TOKEN_SECRET = 'persnal key'

# Authenticate using your keys and tokens

auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

# Create the API object

api = tweepy.API(auth)

def get_followers_count(screen_name):
    user = api.get_user(screen_name=screen_name)  # Update this line
    return user.followers_count

# Replace 'screen_name' with the desired Twitter account's screen name

screen_name = 'account_x'
followers_count = get_followers_count(screen_name)

print(f'The number of followers for {screen_name} is: {followers_count}')

错误信息

Forbidden: 403 Forbidden
453 - 你当前拥有Essential访问权限,该权限仅可访问Twitter API v2端点。如果需要访问此端点,你需要通过开发者门户申请Elevated访问权限。


解答

2023年2月9日之后,免费的Essential访问权限(对应Twitter API v2)仍可获取指定账号的粉丝数,你遇到403错误的核心原因是:原代码使用的是Twitter API v1.1的接口(api.get_user属于v1.1端点),而Essential权限仅允许访问v2的API端点。

修正后的代码(使用API v2)

import tweepy

# 替换为你的密钥和令牌
API_KEY = 'your_api_key'
API_SECRET_KEY = 'your_api_secret_key'
ACCESS_TOKEN = 'your_access_token'
ACCESS_TOKEN_SECRET = 'your_access_token_secret'

# 初始化Twitter API v2客户端
client = tweepy.Client(
    consumer_key=API_KEY,
    consumer_secret=API_SECRET_KEY,
    access_token=ACCESS_TOKEN,
    access_token_secret=ACCESS_TOKEN_SECRET
)

def get_followers_count(screen_name):
    # 通过用户名获取用户信息,指定返回包含粉丝数的public_metrics字段
    response = client.get_user(username=screen_name, user_fields=['public_metrics'])
    if response.data:
        return response.data.public_metrics['followers_count']
    return None

# 替换为目标账号的用户名
screen_name = 'account_x'
followers_count = get_followers_count(screen_name)

if followers_count:
    print(f'{screen_name}的粉丝数为:{followers_count}')
else:
    print(f'无法获取{screen_name}的粉丝信息')

关键说明

  • 改用Tweepy的Client类对接API v2,替代原代码中对应v1.1的API类
  • 调用get_user时必须指定user_fields=['public_metrics'],才能获取包含粉丝数的公开指标数据
  • 免费的Essential权限有调用次数限制,但获取单用户粉丝数的操作在免费额度内完全可用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:05:09