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

标签 python python-3.x urllib python-3.4

我正在尝试将 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/

相关文章:

python - 在新列中计算数据框中的逗号分隔字符串

python - 从文本文件中检索随机预格式化的文本

python - 为什么 super().__init__ 没有自引用?

python - CouchDB urlencode Python

python - 为使用 urllib.urlretrieve 下载的文件添加时间戳

python - 基于 2 个数据帧的 pandas 高效数据操作

python - 如何保护 Python 3 中套接字客户端和服务器之间传输的消息的安全?

python - 是否可以通过多个 TCP 客户端远程使用 Python 的 cmd 模块?

python 3,错误处理urllib请求

Python YahooFinancials 结合 mysql 连接器导致 SSL 错误