While循环中的KeyError

时间:2018-06-05 20:09:07

标签: python loops if-statement while-loop python-2.6

我正在尝试遍历分页网址。我在第一页找到分页URL,转到它,在第二页找到它,转到它,直到最后一页。但是,我得到一个KeyError,这是最后一页没有分页的结果。但是,我认为我的方程会抓住,因为我的陈述将是假的,循环停止。

response1 = requests.get("api.weather.gov/alerts?limit=100") # request API
data1 = response1.json()
pag_object1 = (data1['pagination']['next']) #find pagination object 

while ("pagination" in str(data1)) == True: # while string is found
    response1 = requests.get(pag_object1) # use 1st pag object to make new response
    data1 = response1.json()
    pag_object1 = (data1['pagination']['next']) # redefine pag object

错误:

KeyError: 'pagination'

1 个答案:

答案 0 :(得分:2)

我相信问题如下,在再次检查while循环的条件之前重新定义pag_object1。

我相信正在发生的事情:

  • data1是第二页,仍然包含'分页'对象
  • pag_object1可以被指定为data1包含一个名为' pagination'
  • while条件将评估为True

Last Loop:

  • data1位于最后一页,并且不包含密钥'分页'但是你在检查while循环的条件之前尝试分配pag_object1

这应该解决它:

response1 = requests.get("api.weather.gov/alerts?limit=100") # request API
data1 = response1.json()

# while the pagination string is in the keys 
while "pagination" in data1: 
    # assign the pagination object
    pag_object1 = (data1['pagination']['next']) 

    # use pag_object1 to create a new request for the next page
    response1 = requests.get(pag_object1) 

    # assign the new page to the data1 object
    data1 = response1.json()