运行GET请求循环的Python脚本抛出“KeyError”,但不是每次都抛出

时间:2017-04-04 18:58:21

标签: 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.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_count和true_count的计数总是为0。

2 个答案:

答案 0 :(得分:1)

试试这个解决方案:

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

答案 1 :(得分: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不存在这些物品。