首页 > 解决方案 > 不断迭代分页字典

问题描述

我有一个要求,我从网站获取响应并将其存储为 json。但问题是响应是有限的(分页),它有一个键“__next”,我可以转到下一页并获取数据 。我的逻辑是迭代响应并查找“__next”是否可用,如果可用,则获取值(url)并获取下一页数据并迭代它,直到找不到“__next”键。

这是回应

{
"results":[], 
"__next": "next page url"
}

我写了一个函数,我可以使用 url 获取结果。get_response("下一页网址")

这是我的响应功能

def response_function(url_in):
    headers = {'Authorization':access_token ,'content-type': 'application/x-www-form-urlencoded','Accept':'application/json'}
    r = requests.get(url_in, headers=headers)
    response = json.loads(r.content)
    print("inside for response function")
    return response.values()
response1 = response_function('first url')
skip_tokens = []
for i in response1:
    if  "__next" in i:
        # print(i["__next"])
        skip_tokens.append(i["__next"])

标签: pythonpython-3.xdictionary

解决方案


考虑到您的get_response函数返回字典:

next_page_key = "__next"
partial_response = get_response("first_page_url")
while partial_response.get(next_page_key):
    next_url = partial_response.pop(next_page_key, None)
    partial_response.update(get_response(next_url))


推荐阅读