处理大量数据并请求API

时间:2020-03-22 19:57:55

标签: python python-3.x api

我有很多邮政编码(超过12,000个),需要从API请求并保存响应。

我当前的解决方案是单独请求它们,但python返回 RecursionError: maximum recursion depth exceeded during compilation 超过37,000条线。

我正在寻找一种更简单的方法来请求所有邮政编码并保存响应。

下面是用于一次请求一个邮政编码并保存的代码

邮政编码存储在Excel电子表格中。

# Import Libraries
import urllib.parse
import requests
from datetime import datetime

# Call the API
main_api = 'https://doitonline.york.gov.uk/BinsApi/EXOR/getWasteCollectionsForPostCode?'
postcode = "YO1 6EH"

url = main_api + urllib.parse.urlencode({'postcode': postcode})

json_data = requests.get(url).json()

print(json_data)
now = datetime.now()

saveFile = open("test"+str(now)+".txt", "w")
saveFile.write(str(json_data))
saveFile.close()

谢谢, 本

1 个答案:

答案 0 :(得分:0)

哼,您可能永远不会在这里创建尽可能多的变量。如果您的年龄在30-40岁之间,您真的应该有所不同,那么36,000 ...


所以,现在:

  1. 将所有邮政编码逐行存储在文本文件"postCodes"
  2. 打开文件,然后遍历邮政编码以发出请求并将结果保存到输出文件"test" + str(now) + ".txt"
main_api = 'https://doitonline.york.gov.uk/BinsApi/EXOR/getWasteCollectionsForPostCode?'
now = datetime.now()

with open("postCodes") as postcodes,\ 
     open("test" + str(now) + ".txt", "w") as saveFile:

    for postcode in postcodes:
        postcode = postcode.rstrip()
        url = main_api + urllib.parse.urlencode({'postcode': postcode})
        json_data = requests.get(url).json()
        saveFile.write(str(json_data) + "\n")