python - 不断迭代分页字典
问题描述
我有一个要求,我从网站获取响应并将其存储为 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"])
解决方案
考虑到您的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))
推荐阅读
- azure - Azure 自动化 - 如何通过公共 webhook 运行脚本?
- javascript - Angularjs typeahead不显示第二个输入焦点的选项
- angular - 在 Angular 5 中包含节假日
- c++ - 在 C++11 中将指针转换为多维 C 样式数组
- c++ - 从一组有限的类中静态转换为一个类
- java - java.net.NetworkInterface.getNetworkInterfaces() not listing all interfaces for OS X
- c# - c#如何在Word中获取标准字体样式对象
- angular - Unhandled Promise rejection: Failed to execute 'transaction' on 'IDBDatabase' angularfire
- python - 将 python 2 中的脚本迁移到 python 3.x
- python - 具有不同输出计算的 Scikit-learn