我正在尝试遍历分页网址。我在第一页找到分页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'
答案 0 :(得分:2)
我相信问题如下,在再次检查while循环的条件之前重新定义pag_object1。
我相信正在发生的事情:
Last Loop:
这应该解决它:
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()