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

Tweepy运行报错AttributeError: 'API'对象无'followers'属性问题咨询

问题解决方案

报错处理

你遇到的AttributeError: 'API' object has no attribute 'followers'报错,是因为当前使用的Tweepy 4.0及以上版本重构了接口命名,旧版本的followers方法已更名为get_followers,将代码中对应位置的api.followers替换为api.get_followers即可解决该报错。

其他隐藏问题修复

你的代码还存在多个潜在问题,需同步调整:

  • 变量命名违规:你使用Python内置关键字list作为文件对象变量名,会覆盖系统内置的列表功能,建议替换为follower_file这类自定义命名。
  • 登录校验逻辑错误:if(api.verify_credentials):仅判断方法对象是否存在,没有实际执行校验逻辑,需添加括号调用方法:if api.verify_credentials():。
  • 异常处理逻辑缺陷:当前的except块没有区分异常类型,无论是遍历完成触发的终止异常,还是接口限流报错,都会进入休眠逻辑,导致程序遍历结束后依然无限运行。需要分别捕获StopIteration(遍历完成)和tweepy.TweepyException(接口异常)做不同处理。
  • 资源泄漏风险:手动调用close()关闭文件的方式,在程序中途报错时会无法执行,导致文件句柄泄漏,建议用with open()上下文管理器自动管理文件生命周期。
  • 代码冗余:except块内重复写了读取用户、写入文件的逻辑,可以优化合并避免重复。

修复后完整代码

import tweepy
import time
# 填入你的Twitter密钥
consumer_key ='xxx'
consumer_secret='xxx'
access_token='xxx'
access_token_secret='xxx'
twitter_handle='handle'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

with open('twitter_followers.txt','w', encoding='utf-8') as follower_file:
    if api.verify_credentials():
        print('We successfully logged in')

    user_cursor = tweepy.Cursor(api.get_followers, screen_name=twitter_handle).items()

    while True:
        try:
            u = next(user_cursor)
            follower_file.write(f"{u.screen_name}\n")
        except StopIteration:
            break
        except tweepy.TweepyException:
            time.sleep(15 * 60)
            print('We got a timeout ... Sleeping for 15 minutes')

内容的提问来源于stack exchange,提问作者김도흔

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:48:00