运行GET请求循环的Python脚本抛出;KeyError";,但并非每次都如此
我创建了一个python脚本,它允许我运行一个循环来处理几个GET请求。然后,我为每个名为“creative”的字段请求提取值,然后在脚本末尾打印“True”和“False”值的最终计数。下面是我的代码的样子:运行GET请求循环的Python脚本抛出;KeyError";,但并非每次都如此,python,python-2.7,loops,python-requests,Python,Python 2.7,Loops,Python Requests,我创建了一个python脚本,它允许我运行一个循环来处理几个GET请求。然后,我为每个名为“creative”的字段请求提取值,然后在脚本末尾打印“True”和“False”值的最终计数。下面是我的代码的样子: import requests import json false_count = 0 true_count = 0 qa_creatives = open("numbers.txt") arraylist = [] for line in qa_creatives.readlin
import requests
import json
false_count = 0
true_count = 0
qa_creatives = open("numbers.txt")
arraylist = []
for line in qa_creatives.readlines():
arraylist.extend(line.split())
qa_creatives.close()
arraylist = map(int, arraylist)
authorization_code = raw_input("please enter your authorization code: ")
creatives = arraylist
print "Creative Check script is now running, please wait."
for creative in creatives:
url = "http://api.wiki123.com/v1.11/creative?id="+str(creative)
header = {"Authorization": authorization_code}
response = requests.get(url, headers=header)
creative_check = json.loads(response.text)
final_creative_status = creative_check["response"]["creative"]["is_expired"]
#print str(creative) + " expired status: " + str(final_creative_status)
if final_creative_status == False:
false_count += 1
else:
true_count += 1
print "Creative Check Complete:"
print str(false_count) + " creatives are still valid"
print str(true_count) + " creatives have expired"
下面是发出以下GET请求时返回的JSON数据示例:
{
'response': {
'count': 1,
'creative': {
'prime_id': 1092343,
'off_audit': None,
'allow_audit': False,
'allow_ssl_audit': False,
'audit_feedback': None,
'audit_status': 'no_audit',
'backup_upload_status': None,
'brand': {
'category_id': 0,
'id': 1,
'name': 'Unknown'
}
}}}
奇怪的是,这个脚本有时能正常工作,但有时,我会出现以下错误:KeyError:“creative”。我对此感到困惑,因为我的请求每次都应该返回相同的内容,因此,密钥永远不应该更改。有人能告诉我这里可能发生了什么吗?关于如何调试此问题,有什么建议吗?如果某个“创意”正在打破循环,那么排除它的最佳方式是什么?谢谢
更新了我的循环代码:
for creative in creatives:
url = "http://api.wiki123.com/v1.11/creative?id="+str(creative)
header = {"Authorization": authorization_code}
api_response = requests.get(url, headers=header)
creative_check = json.loads(api_response.text)
creative_status = creative_check.get("response",
{}).get("creative{}).get("is_expired", None)
if creative_status is None:
pass
elif creative_status == True:
true_count += 1
else :
false_count += 1
print "Creative Check Complete: "
print str(false_count) + " creatives are still valid"
print str(true_count) + " creatives have expired"
注意:现在,我没有收到返回的密钥错误,但在脚本完成后,我的false\u count和true\u count计数始终为0。您的问题在于:
final_creative_status = creative_check["response"]["creative"]["is_expired"]
您希望访问不存在的json对象。放置一个try-except-KeyError以捕获异常或放置如下条件:
if 'creative' in creative_check["response"].keys():
if 'is_expired' in creative_check["response"]["creative"].keys():
blablabla
我确信json中不存在这些对象。尝试以下解决方案:
for creative in creatives:
url = "http://api.wiki123.com/v1.11/creative?id="+str(creative)
header = {"Authorization": authorization_code}
response = requests.get(url, headers=header)
creative_check = json.loads(response.text)
creative_status = creative_check.get("response", {}).get("creative", {}).get("is_expired", None)
if creative_status is None :
## That means that the key 'is_expired' does not exist. ##
## You can handle this case here or just pass ##
pass
elif creative_status :
# 'is_expired' is True
true_count += 1
else :
# 'is_expired' is False
false_count += 1
显然,有时响应不会返回包含
creative
的词典。这就是我所想的。。。如果一个特定的“创造性”GET请求没有返回带有“创造性”键的数据,有没有一种好方法可以将这些数据吐出来?或者更具体地说,把它们放在一个单独的列表中?。。。您可以捕获键错误
,并相应地处理它。。。否?您可以使用:如果创意检查[“响应”]:(…您的代码在这里…)其他:单独列表+=[创意检查[“响应”]
感谢您的回复。我对Python还是新手:您是指使用“try-except”来剔除错误案例吗?谢谢您的帮助。我已经在我的原始帖子中添加了我的for循环的更新代码。现在,我没有返回任何键错误,但是我的脚本一完成,“false\u count”和“true\u count”的计数总是显示为“0”。我一定是做错了什么。有什么建议吗?谢谢。第10行似乎有语法错误:get(“creative{})
应该是get(“creative”,{})
2.如果false\u count和true\u count都为0,则表示键“is\u expired”不存在。3.能否发布一些json数据以验证“is\u expired”是否存在以及是否为真?如果将If-else排除在for循环之外,则它仅适用于最后一个创造性\u状态
,这是一个缩进这是我的问题;在将if语句添加到循环中之后,脚本工作得非常好。再次感谢!我很高兴能提供帮助。