Python 保持循环,直到API响应不再包含特定密钥

Python 保持循环,直到API响应不再包含特定密钥,python,python-3.x,while-loop,python-requests,Python,Python 3.x,While Loop,Python Requests,我正在从一个API中检索一个JSON响应,该API包含一个“下一个”字段,如果还有另一个结果页面(该页面一次只显示20个结果)。我希望循环继续跟随这些“下一个”URL(在每个页面上添加值),直到“下一个”键不在响应中 我尝试了两种不同的方法,但要么有效,只抓取第一页,要么出现错误,如:JSONDecodeError:Expecting value:line 1 column 1(char 0) 这是到目前为止的代码,希望我已经解释了我要实现的目标 totalOrderCount = 0 tota

我正在从一个API中检索一个JSON响应,该API包含一个“下一个”字段,如果还有另一个结果页面(该页面一次只显示20个结果)。我希望循环继续跟随这些“下一个”URL(在每个页面上添加值),直到“下一个”键不在响应中

我尝试了两种不同的方法,但要么有效,只抓取第一页,要么出现错误,如:
JSONDecodeError:Expecting value:line 1 column 1(char 0)

这是到目前为止的代码,希望我已经解释了我要实现的目标

totalOrderCount = 0
totalOrderAmount = 0

response = session.get(url+'/ordertransactions').json()

while 'next' in response:
    nextUrl = response['next']
    for i in response['orders']:
        totalOrderCount = totalOrderCount + 1
        totalOrderAmount = totalOrderAmount + i['amount']
    response = session.get(nextUrl).json() # Grab next page of results and perform the above actions again
else:
    for i in response['orders']:
        totalOrderCount = totalOrderCount + 1
        totalOrderAmount = totalOrderAmount + i['amount']

print(totalOrderCount)
print(totalOrderAmount)

谢谢你的帮助

错误消息告诉您响应不是JSON——它无法理解它。通常的原因是页面出错并返回HTML

我建议你试试

print(session.get(nextur.content[:1000])


查看请求所看到的内容。

解决了这个问题,问题是URL

API请求使用以下域:
https://adminapi.prod-environment.com

而下一个URL字符串是:
https://admin.prod-environment.com


com之后的一切都是一样的,所以我不得不简单地去掉url的开头,一切都很好

请将完整的错误回溯添加到您的问题中。您仅在第一个请求中解码json。