使用Mastodon Python API无法获取username的问题求助
解决Mastodon Python API访问username字段的错误问题
嘿,我来帮你搞定这个问题!你遇到的TypeError: 'instancemethod' object has no attribute '__getitem__'错误,核心原因是你搞错了访问方式——mastodon.account其实是一个实例方法,不是直接存储用户数据的字典,所以不能直接用['username']去取值。
要顺利提取username字段,你需要先调用对应的API方法拿到用户的账号数据字典,再从中提取目标字段。具体操作如下:
1. 获取账号数据
根据你的需求,分两种常见场景处理:
- 获取当前登录用户的信息:使用
account_verify_credentials()方法,无需额外参数就能拿到自己的账号数据:
# 获取当前登录用户的完整账号信息 my_account = mastodon.account_verify_credentials()
- 获取特定用户的信息:需要知道目标用户的ID,传入
account()方法中:
# 替换为你要查询的用户ID target_user_id = 123456 target_account = mastodon.account(target_user_id)
2. 提取username字段
拿到账号数据字典后,就可以正常通过键名访问username字段了:
# 打印当前登录用户的username print(my_account['username']) # 打印目标用户的username print(target_account['username'])
错误原因复盘
你之前的代码只完成了应用创建和登录流程,但没有调用任何获取账号信息的方法。mastodon.account是用来获取指定用户信息的可调用方法,本身不是存储数据的字典,直接用['username']访问自然会触发错误。
内容的提问来源于stack exchange,提问作者amit ncert
相关产品推荐
相关产品推荐

