Python:将URL列表中的结果转储到JSON文件时,在每个项之后添加延迟
我有下面的脚本,它将几个API调用的列表的结果放入一个列表,然后将该列表写入一个JSON文件,但我限制为每秒2个调用Python:将URL列表中的结果转储到JSON文件时,在每个项之后添加延迟,python,json,api,url,time,Python,Json,Api,Url,Time,我有下面的脚本,它将几个API调用的列表的结果放入一个列表,然后将该列表写入一个JSON文件,但我限制为每秒2个调用 with open('data.json', 'a') as fp: json.dump([requests.get(url).json() for url in urls], fp, indent=2) 使用时间睡眠(0.5)是否可以实现这一点?如果是这样的话,我不太确定如何在这个阶段 任何帮助都将不胜感激 您可以先收集数据,然后在最后对其进行JSON编码并将其记录下
with open('data.json', 'a') as fp:
json.dump([requests.get(url).json() for url in urls], fp, indent=2)
使用时间睡眠(0.5)
是否可以实现这一点?如果是这样的话,我不太确定如何在这个阶段
任何帮助都将不胜感激 您可以先收集数据,然后在最后对其进行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()
注入其中。太棒了!谢谢@zwer