Tweepy中get_user()参数错误求助:获取Twitter用户ID失败
问题解决:
get_user() 参数错误及脚本完善 错误原因
错误get_user() takes 1 positional argument but 2 were given是因为Tweepy的get_user方法要求使用关键字参数传递用户名,而非位置参数。新版本Tweepy(如v4+)不再支持直接传位置参数,必须指定参数名(如screen_name或username)。
另外你的代码还有两处问题:
handle[1:-1]会错误截断用户名(若csv中用户名无引号,会丢失首尾有效字符)- 未实现将提取的ID写入
ids.csv的核心逻辑
修复后的代码
import tweepy import time import csv import sys consumer_key = "CONSUMER_KEY" consumer_secret = "CONSUMER_SECRET" access_token = "ACCESS_TOKEN" access_token_secret = "ACCESS_TOKEN_SECRET" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) def get_user_ids(): handles = [] # 读取csv中的用户名,过滤空值 with open("list.csv", "r") as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in reader: for elem in row: handles.extend([h.strip() for h in elem.split(',') if h.strip()]) # 将提取的ID写入ids.csv with open("ids.csv", "w", newline='') as outfile: writer = csv.writer(outfile) for handle in handles: try: # 用关键字参数传递用户名,自动去除可能的@前缀 u = api.get_user(screen_name=handle.lstrip('@')) time.sleep(6) user_id = u._json['id'] print(user_id) sys.stderr.write(str(user_id) + "\n") writer.writerow([user_id]) except Exception as e: print(f"处理{handle}时出错: {e}") if __name__ == '__main__': get_user_ids()
关键修复点
- 将
api.get_user(handle[1:-1])改为api.get_user(screen_name=handle.lstrip('@')):使用关键字参数适配Tweepy版本,同时兼容带@前缀的用户名 - 新增
ids.csv写入逻辑,完成脚本核心需求 - 优化用户名读取逻辑,过滤空字符串,减少无效请求
- 异常提示添加出错用户名,便于定位问题
内容的提问来源于stack exchange,提问作者WiseUp2RiseUp
相关产品推荐
相关产品推荐

