【问题标题】:How to write a python loop to change a value for a dictionary key in API request?如何编写 python 循环来更改 API 请求中字典键的值?
【发布时间】:2020-04-01 21:23:39
【问题描述】:

我正在编写一个提供分页结果的 API 请求。 要从下一页获取结果,我需要取一个 'next_page_cursor' 的值并将其放入我的请求参数中,即字典。

这是我迄今为止尝试过的。需要不断更改 params 中的 cursor 值,直到没有更多页面为止。

params = {'title': 'Cybertruck',
          'per_page':100,
          'cursor': '*'
         }


response = requests.get("https://api.aylien.com/news/stories", 
                       headers = headers,   params=params).json()

if "next_page_cursor" in response:
    cursor = response["next_page_cursor"]

【问题讨论】:

  • 您没有明确地将其传递为'cursor': * - 这是无效的,您最初的params dict 是什么?
  • 初始字典是我在帖子中的内容,'cursor' 的默认值是 * 我需要将其替换为 'next_page_cursor"
  • 你不能明确地将* 作为值——这会引发SyntaxError: invalid syntax 。更新您的代码
  • 谢谢,已更新。忘记使用引号

标签: python api loops python-requests


【解决方案1】:

您可以使用while 循环:

params = {
    "title": "Cybertruck",
    "per_page": 100,
    "cursor": "initial_cursor"
}

def make_request(params)
    return requests.get("https://api.aylien.com/news/stories", 
                        headers=headers, params=params).json()
result = []
response = make_request(params)
while "next_page_cursor" in response:
    params["cursor"] = response["next_page_cursor"]
    response = make_request(params)
    result.append(response["information_your_are_interested_in"])

【讨论】:

  • 感谢@nicoring!结果字典只给了我最后一页的值,而不是所有页面的值。你知道如何改变它吗?否则 - 这非常有帮助,我更接近我正在寻找的东西
  • 你必须在某处积累结果。这取决于response 在这种情况下的样子。我会更新答案,给你一些指导。
猜你喜欢
  • 2022-01-02
  • 2013-11-24
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 2013-08-05
  • 2022-08-03
  • 2011-05-22
相关资源
最近更新 更多