使用Tweepy查询Twitter用户详情时,如何跳过已暂停用户继续执行?
解决Tweepy遇到暂停用户时程序终止的问题
这个问题很典型——当Tweepy请求到已被暂停的用户账号时,会直接抛出TweepError异常中断整个循环,导致剩余用户的查询无法继续。咱们只需要给查询逻辑加上异常捕获与处理,就能轻松跳过错误用户,让程序正常跑完所有用户。
核心思路
捕获tweepy.TweepError异常,通过错误码63(对应“User has been suspended”)识别暂停用户,打印提示后直接跳过该用户,继续执行下一个循环迭代。
修改后的代码示例
方式1:在循环中直接处理异常(推荐,逻辑更清晰)
import tweepy def get_user_details(api, username): # 把api作为参数传入,避免全局变量依赖 userobj = api.get_user(username) return userobj if __name__ == '__main__': # 认证部分保持不变 auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(oauth_token, oauth_token_secret) api = tweepy.API(auth) for username in df.username: print(f"正在查询用户: {username}") try: user_info = get_user_details(api, username) print(f"位置信息: {user_info.location}") except tweepy.TweepError as e: # 检查是否是用户暂停的错误 if hasattr(e, 'api_code') and e.api_code == 63: print(f"⚠️ 用户 {username} 已被暂停,跳过该用户") else: # 其他Tweepy错误(比如限流、用户不存在等)也可以针对性处理 print(f"❌ 查询用户 {username} 时出错: {str(e)}") # 无论哪种错误,都继续下一个用户 continue
方式2:在函数内部处理异常
如果希望把异常逻辑封装在get_user_details里,可以这样修改:
import tweepy def get_user_details(api, username): try: userobj = api.get_user(username) return userobj except tweepy.TweepError as e: if e.api_code == 63: print(f"⚠️ 用户 {username} 已被暂停") return None else: print(f"❌ 查询错误: {str(e)}") return None if __name__ == '__main__': auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(oauth_token, oauth_token_secret) api = tweepy.API(auth) for username in df.username: print(f"正在查询用户: {username}") user_info = get_user_details(api, username) if user_info is not None: print(f"位置信息: {user_info.location}")
额外提示
- 除了错误码
63,Tweepy还有其他常见错误码(比如88是API限流),如果需要可以扩展异常处理逻辑,比如遇到限流时添加等待时间后重试。 - 把
api作为参数传入函数,避免依赖全局变量,让代码更模块化、可复用。
内容的提问来源于stack exchange,提问作者Michelle Huang
相关产品推荐
相关产品推荐

