我有以下脚本,该脚本将多个API调用的列表结果放入列表中,然后将该列表写入JSON文件,但每秒只能进行2次调用。
with open('data.json', 'a') as fp:
json.dump([requests.get(url).json() for url in urls], fp, indent=2)
是否可以使用time.sleep(0.5)
来实现?如果是这样,我不太确定如何达到这个阶段。
任何帮助将不胜感激!
答案 0 :(得分:0)
您可以首先收集数据,然后最后对其进行JSON编码并将其记录下来:
import json
import requests
import time
results = [] # a list to hold the results
for url in urls: # iterate over your URLs sequence
results.append(requests.get(url).json()) # fetch and append to the results
time.sleep(0.5) # sleep for at least half a second
with open("data.json", "a") as f: # not sure if you want to append, tho
json.dump(results, f, indent=2) # write everything down as JSON
实际上,您正在执行相同的操作,只是您需要拆解列表理解部分,以便可以向其注入time.sleep()
。