使用Tweepy访问属性触发AttributeError:'Response'对象无对应属性求助
解决Tweepy OAuth2认证后无法访问推文/用户属性的问题
你遇到的问题核心是:OAuth2认证模式下,Tweepy返回的是Response包装对象,而非直接的用户/推文实体,之前的认证方式可能直接返回实体实例,所以现在不能直接通过.text/.username这类属性访问。
具体修复步骤:
- 所有API调用的返回结果,先通过
.data属性提取实际的实体数据:- 获取用户信息时,
api.get_user返回的Response里,.data才是用户对象,之后再调用.username等属性 - 获取单条推文时,
api.get_tweets支持传入多个ID,所以.data是推文列表,取第一个元素([0])后再访问.id - 获取用户推文列表时,
.data是推文对象的列表,需要遍历每个推文来访问.text
- 获取用户信息时,
修改后的代码示例:
# 获取用户信息并打印username user_response = api.get_user(username='Redistrict') print(user_response.data.username) # 获取单条推文并打印id tweet_response = api.get_tweets(ids="74820061") print(tweet_response.data[0].id) # 获取用户推文列表并打印每条推文的text tweets_response = api.get_users_tweets(id="74820061", exclude="retweets", tweet_fields="text") for tweet in tweets_response.data: print(tweet.text)
如果需要获取分页的更多推文,可以查看response.meta里的next_token参数,传入下一次调用的pagination_token参数即可。
内容的提问来源于stack exchange,提问作者badatcoding
相关产品推荐
相关产品推荐

