gpt4 book ai didi

python - 超时错误,从 url 获取图像 - Python

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:33 25 4
gpt4 key购买 nike

我正在尝试将 url 列表中的 jpeg 保存到文件中。此代码频繁且随机地超时。它最多保存了 113 个 jpeg,还有更多,有时在超时之前只保存了 10 个。有没有办法让等待,这样就不会发生超时?我曾尝试在评论部分中 sleep ,但没有成功。感谢您的反馈!

这是超时错误消息:

enter image description here

import urllib.request
import urllib
import codecs
from urllib import request
import time
import csv

class File:
def __init__(self, data):
self.data = data

file = File("1")

with open("file.csv", encoding = "utf8") as f1:
file.data = list(csv.reader(f1, skipinitialspace = True))

for i in file.data[1:]:
if len(i[27]) != 0:
#i[14] creates a unique jpeg file name in the dir
image = open('C:\\aPath'+i[14]+'.JPG', 'wb')
path = 'aPath' + i[14] + '.JPG'

#time.sleep(2) Tried sleep here, didn't work

#i[27] is a working jpeg url
urllib.request.urlretrieve(i[27], path)

image.close()
print('done!')

最佳答案

没有办法阻止异常。您需要捕获异常并重试。

...

for i in file.data[1:]:
if not i[27]:
continue
path = 'aPath' + i[14] + '.JPG'
while True: # retry loop
try:
urllib.request.urlretrieve(i[27], path)
break # On success, stop retry.
except TimeoutError:
print('timeout, retry in 1 second.')
time.sleep(1)

顺便说一句,如果您使用urllib.request.urlretrieve,则不需要打开文件。

关于python - 超时错误,从 url 获取图像 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com