使用Twitter API(学术权限)导出CSV添加用户信息报错求助
解决Twitter API获取用户信息的KeyError问题
你的问题核心是Twitter API v2的用户信息不会嵌套在tweet数据中:当你指定expansions=author_id时,用户的username、name、description等数据会被放在响应的includes.users数组里,而非tweet对象内部,所以直接从tweet里取这些字段会触发KeyError。
修改后的append_to_csv函数
def append_to_csv(json_response, fileName): counter = 0 # 将用户列表转为字典,用用户ID作为键,方便快速匹配 users_dict = {} if 'includes' in json_response and 'users' in json_response['includes']: for user in json_response['includes']['users']: users_dict[user['id']] = user csvFile = open(fileName, "a", newline="", encoding='utf-8') csvWriter = csv.writer(csvFile) for tweet in json_response['data']: author_id = tweet['author_id'] # 从字典中匹配对应的用户对象,处理用户信息缺失的情况 user = users_dict.get(author_id, {}) # 提取用户信息,默认值为空字符串避免KeyError username = user.get('username', '') name = user.get('name', '') description = user.get('description', '') created_at = dateutil.parser.parse(tweet['created_at']) text = tweet['text'] geo = tweet['geo']['place_id'] if ('geo' in tweet) else " " tweet_id = tweet['id'] lang = tweet['lang'] retweet_count = tweet['public_metrics']['retweet_count'] reply_count = tweet['public_metrics']['reply_count'] like_count = tweet['public_metrics']['like_count'] quote_count = tweet['public_metrics']['quote_count'] source = tweet['source'] res = [author_id, username, name, description, created_at, text, geo, tweet_id, lang, like_count, quote_count, reply_count, retweet_count, source] csvWriter.writerow(res) counter += 1 csvFile.close()
修改要点说明
- 构建用户字典:先把
includes.users转成以用户ID为键的字典,这样通过推文的author_id可以快速找到对应用户,避免重复遍历用户列表。 - 使用
get方法安全取值:用dict.get(key, 默认值)替代直接索引,即使某个用户字段缺失(比如未设置个人描述),也不会触发KeyError,而是返回预设的空字符串。 - 处理用户信息缺失场景:如果API响应中未返回某个用户的信息(极端情况),
users_dict.get(author_id, {})会返回空字典,后续get方法会取默认值,保证程序正常运行。
内容的提问来源于stack exchange,提问作者socialscientist90
相关产品推荐
相关产品推荐

