缩短此代码...从多个 GET 请求附加 JSON 数据,然后转储到单个 Excel 文件 Headers

Shorten this code... Append JSON data from Multiple GET requests, then dump into single Excel File with Headers

我对 Python 很陌生。

我正在使用的 API 每个请求限制为 1000 个结果。 我正在尝试获取特定日期范围内的所有 results/data,对于此示例为 1 个月。

在我开始之前,我 运行 一个 GET 请求来查看总共需要导出多少结果。

对于此示例,总数 = 14,841。然后我使用 1001、2001、3001 等“开始”参数创建 15 个 queries/requests,每个 1000 个,然后获取每个请求的响应并将其保存到包含 JSON 的 txt 文件中数据.

我确信有一种方法可以使用 Python 来缩短此代码和流程。 有时总计超过 500,000 个结果,这迫使我执行 500 多个请求。

下面是 5 个请求/查询的示例。

  1. 如何缩短此代码以将多个查询和数据合并到 1 个文件中?

    导入请求

    url = "https://api.leadspedia.com/core/v2/leads/getAll.do"

    headers = { 'Content-Type': "application/json", 'Authorization': "基本 XYZ" }

    querystring = {"fromDate":"2020-04-01","toDate":"2020-04-30","start":"0","limit":"1000"} querystring2 = {“fromDate”:“2020-04-01”,“toDate”:“2020-04-30”,“start”:“1001”,“limit”:“1000”} querystring3 = {“fromDate”:“2020-04-01”,“toDate”:“2020-04-30”,“start”:“2001”,“limit”:“1000”} querystring4 = {“fromDate”:“2020-04-01”,“toDate”:“2020-04-30”,“start”:“3001”,“limit”:“1000”} querystring5 = {"fromDate":"2020-04-01","toDate":"2020-04-30","start":"4001","limit":"1000"}

    response = requests.request("GET", url, headers=headers, params=querystring) response2 = requests.request("GET", url, headers=headers, params=querystring2) response3 = requests.request("GET", url, headers=headers, params=querystring3) response4 = requests.request("GET", url, headers=headers, params=querystring4) response5 = requests.request("GET", url, headers=headers, params=querystring5)

    file = open("out1.txt", "wb") file.write(response.content) file.close()

    file = open("out2.txt", "wb") file.write(response2.content) file.close()

    file = open("out3.txt", "wb") file.write(response3.content) file.close()

    file = open("out4.txt", "wb") file.write(response4.content) file.close()

    file = open("out5.txt", "wb") file.write(response5.content) file.close()

您可以创建一个布尔值来指示您是否仍在获取新的有效结果并使用它进行 while 循环:

query_number = 1
start = 0
more_to_query = True

while more_to_query:
  querystring={"fromDate":"2020-04-01","toDate":"2020-04-30","start":str(start),"limit":"1000"} 
  response = requests.request("GET", url, headers=headers, params=querystring) 
  file = open("out" + str(query_number) + ".txt", "wb")
  file.write(response.content) 
  file.close()
  start += 1000
  query_number += 1
  # set more_to_query to False when you detect you're no longer receiving new valid responses