You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Requests调用IP地址API时如何检查响应中是否存在error字段

安全检查IP API响应中的error字段

你的问题很典型——直接访问字典里不存在的键肯定会触发KeyError,这就是请求有效时控制台报错的原因。这里有几种简单可靠的解决方法:

方法1:使用字典的get()方法(推荐)

dict.get(key, default)是处理这种场景最简洁的方式,它会尝试获取指定键的值,如果键不存在,就返回你设定的默认值。这样完全不会触发键不存在的错误:

API = f'https://ipapi.co/{args[0]}/json/'
response = requests.get(API)
json_data = response.json()

# 若error字段不存在,默认返回False
if json_data.get('error', False):
    print('There was an error with the API')
else:
    countryname = json_data['country_name']
    countrycode = json_data['country_code']
    region = json_data['region']

方法2:用in关键字检查键是否存在

如果你想更明确地判断键的存在性,可以先用in运算符检查json_data里是否包含error字段,再去访问它的值:

API = f'https://ipapi.co/{args[0]}/json/'
response = requests.get(API)
json_data = response.json()

# 先确认error字段存在,再判断其值
if 'error' in json_data and json_data['error']:
    print('There was an error with the API')
else:
    countryname = json_data['country_name']
    countrycode = json_data['country_code']
    region = json_data['region']

额外建议:先检查HTTP状态码

为了让代码更健壮,建议先判断请求本身是否成功(比如HTTP状态码为200),避免在请求失败时解析JSON出现异常:

API = f'https://ipapi.co/{args[0]}/json/'
response = requests.get(API)

if response.status_code != 200:
    print(f'Request failed with status code: {response.status_code}')
else:
    json_data = response.json()
    if json_data.get('error', False):
        print('There was an error with the API')
    else:
        countryname = json_data['country_name']
        countrycode = json_data['country_code']
        region = json_data['region']

这样不管是请求层面的错误,还是API返回的业务错误,都能被妥善处理啦。

内容的提问来源于stack exchange,提问作者TrueVulpis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:32:35