如何在Python中自动重连IOError

0 投票
2 回答
1715 浏览
提问于 2025-04-17 08:33

我正在用Python抓取链接,结果突然断开了连接,显示了下面的错误信息。

IOError: [Errno socket error] [Errno 110] Connection timed out

我该怎么重新连接到同一个链接呢?

比如说

import urllib

a = 'http://anzaholyman.files.wordpress.com/2011/12/zip-it.gif'
image = urllib.URLopener()
image.retrieve(a,'1.jpg')

2 个回答

1

如果在加载你的图像时真的出现了问题,那么一个简单的循环可能会一直运行下去,这样你的程序就会看起来像是卡住了。为了避免这种情况,我通常会使用一个计数器:

tries = 5
while tries:
    try:
        image.retrieve(a,'1.jpg')
        break
    except IOError:     
        tries -= 1     #and maybe with 0.1-1 second rest here
else:
    warn_or_raise_something

为了防止临时性的问题,我有时还会在连续尝试失败后,使用一个延迟(比如time.sleep)来间隔一下再试。

2

你可以简单地使用 try..except 这种写法:

import urllib

a = 'http://anzaholyman.files.wordpress.com/2011/12/zip-it.gif'
image = urllib.URLopener()
while True:
    try:
        image.retrieve(a,'1.jpg')
        break
    except IOError:
        pass

撰写回答