如何使用Python读取API上的下一页?

2024-09-30 22:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要关于如何做一个循环的帮助,所以每次我发出GET请求时,它总是来自API的新页面。在

我从第一反应开始。它包含下一页的参数next_key

{
  "result": [
    {
      ...,
      ...
    }
  ],
  "next_key": 123
 }

下面是我目前的尝试

^{pr2}$

完整的url包括limit count、limit size和curr key如下https://flespi.io/gw/channels/all/messages?data=%7B%22curr_key%22%123%2C%22limit_count%22%3A100%2C%22limit_size%22%3A10000%7D

如您所见,这只返回第二个页面jsonData["next_key"]。我想做的是,对于每个GET请求,程序将读取next_key,并将其放在下一个GET请求中。在

我正在考虑在curr_key上使用增量,但是键是随机的,而且我也不知道有多少页。在

我相信一定有一个简单的解决办法,但显然我想不起来。谢谢你的帮助和建议。在


Tags: keyhttpsapiurl参数sizegetcount
1条回答
网友
1楼 · 发布于 2024-09-30 22:27:39

试试这个

has_next_key = False
nextKey = ""

if "next_key" in jsonData:
    has_next_key = True
    nextKey = jsonData["next_key"]

while has_next_key:
    data = {"limit_count":100, "limit_size":10000,"curr_key":nextKey}
    params = {"data":json.dumps(data, separators=(",", ":"))}

    req = requests.get(url, params=params, headers=headers).json()  ## this should do GET request for the third page and so on...
    if "next_key" in req:
        nextKey = req["next_key"]
        print nextKey # this returns "3321" which is the value for "next_key" in second page
    else:
        has_next_key = False
        # no next_key, stop the loop

相关问题 更多 >