首页 > 解决方案 > python请求模块无法使用错误信息

问题描述

我不知道如何在标题中用词,但基本上我有一个 IP 地址 API,如果 API 有效,它会提供数据,如果不是,它会提供错误消息(https://ipapi.co/ {args[0]}/json/)。这个 API 的问题是成功时没有错误名称。所以我做了一个 if 语句来检查 API 是否返回错误:

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

if json_data['error'] == True:
   print(f'There was an error with the API') # something like this.
else:
countryname = json_data['country_name']
countrycode = json_data['country_code']
region = json_data['region']

这样做的问题是,如果返回错误,那么它会这样说,但如果没有,我只会收到一个控制台错误,因为它是一个有效的 IP,因此没有返回错误名称。无论如何我可以检查是否有一个名为错误的名称?如果我的措辞不对,我很抱歉,英语不是我的第一语言。

标签: python

解决方案


您可以get()使用dict. None如果未找到密钥,它将返回,而不是引发异常:

if json_data.get('error'):
   print(f'There was an error with the API') # something like this.
else:
    countryname = json_data['country_name']
    countrycode = json_data['country_code']
    region = json_data['region']

推荐阅读