Python:在将URL结果转换为JSON文件时,在每个项目后添加延迟

问题描述 投票:0回答:1

我有以下脚本,它将几个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)可以达到这个目的吗?如果是这样,我不太确定如何在这个阶段。

任何帮助,将不胜感激!

python json api url time
1个回答
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()了。

© www.soinside.com 2019 - 2024. All rights reserved.