簡體   English   中英

Python:將結果從URL列表轉儲到JSON文件時,在每個項目之后添加延遲

[英]Python: adding a delay after each item when dumping results from a list of URLs into a JSON file

我有以下腳本,該腳本將幾個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)呢? 如果是這樣,我不太確定如何達到這個階段。

任何幫助,將不勝感激!

您可以先收集數據,然后最后對它進行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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM