Python网络爬虫线程Thread-1出现KeyError: 'organization'错误求助
解决Clicky.com API爬虫提取organization字段的KeyError问题
问题原因
API返回的JSON数据中,部分items对象缺失organization字段,直接通过item["organization"]访问会触发KeyError。
解决方案
采用两种安全访问字典字段的方式,避免报错:
方式1:使用字典get()方法(推荐)
get()方法允许指定键不存在时的默认值,不会抛出异常:
organization = item.get("organization", "未知组织")
方式2:先判断字段是否存在
在访问前检查键是否存在,再赋值:
if "organization" in item: organization = item["organization"] else: organization = "未知组织"
修改后的完整代码
import requests import json from threading import Thread from timed_count import timed_count def periodic(): for count in timed_count(60): response = requests.get(api_url, params=params) if response.status_code == 200: data = response.json() arr = [] for element in data: time_items = element["dates"][0]["items"] for item in time_items: ip_address = item["ip_address"] # 安全获取organization字段 organization = item.get("organization", "未知组织") arr.append(organization) print(organization) # 使用with语句自动管理文件,无需手动关闭 with open("visitors_list", "w") as data_file: json.dump(data, data_file, indent=4) else: print(f"Error connecting to Clicky.com API.\nError: {response.status_code}") thread = Thread(target=periodic) thread.start()
额外优化:用with语句处理文件操作,自动关闭文件避免资源泄漏;修改变量名i为item,提升代码可读性。
内容的提问来源于stack exchange,提问作者Dre1n
相关产品推荐
相关产品推荐

