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

如何修复Twython中的AttributeError: 'dict' object has no attribute 'append'错误

解决Twython获取Twitter关注者脚本的两个问题

你遇到的两个问题本质上都是循环变量名与结果列表名重复导致的,这是新手很容易踩的小坑,咱们来一步步修复:

错误原因分析

1. AttributeError: 'dict' object has no attribute 'append'

你一开始初始化了空列表 followers = [] 用来存储关注者用户名,但在循环中写了:

for followers in get_followers["users"]:

这里的followers会被重新赋值为遍历到的每个用户字典(get_followers["users"]中的每个元素都是用户信息的字典)。当你执行followers.append(...)时,followers已经不是列表,而是一个字典对象,所以会抛出这个错误。

2. 注释第19行后出现异常输出

注释掉followers.append(...)后,循环结束时followers变量保存的是最后一个用户的字典。后续执行"".join(followers)时,Python会把字典的所有键(比如id、screen_name)拼接成字符串,所以你看到了那些杂乱的键名输出。

修正后的完整代码

from twython import Twython
import datetime

# 填入你的Twitter API密钥
app_key = ""
app_secret = ""
oauth_token = ""
oauth_token_secret = ""

twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)

followers = []
datestamp = datetime.datetime.now().strftime("%Y-%m-%d")
username = input("what is your username: ")
next_cursor = -1

# 关键:把循环变量改为follower(单数),避免覆盖结果列表followers
while next_cursor != 0:
    get_followers = twitter.get_followers_list(screen_name=username, count=200, cursor=next_cursor)
    for follower in get_followers["users"]:
        # Python3默认支持Unicode,无需手动encode
        followers.append(follower["screen_name"])
    next_cursor = get_followers["next_cursor"]

# 使用with语句自动管理文件,无需手动调用close
with open(f"{username}-{datestamp}.txt", "w", encoding="utf-8") as followers_text:
    # 修正字符串格式化的多余括号,添加换行分隔用户名
    header = f"{username} has {len(followers)} followers ({datestamp}):\n"
    followers_text.write(header)
    followers_text.write("\n".join(followers))

额外优化说明

  1. 循环条件改为next_cursor != 0,因为Twitter API返回的next_cursor为0时表示没有更多数据了,比原代码的while(next_cursor)逻辑更清晰。
  2. Python3中不需要手动encode("utf-8"),直接存储字符串即可,写入文件时指定encoding="utf-8"避免乱码。
  3. 使用with语句处理文件,会自动关闭文件,避免因程序异常导致文件未关闭的问题。
  4. 输出时给每个用户名添加换行,让文件内容更易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:36:37