Python howto异常句柄<urlopen error =“”[errno =“”54] =“”connection =“”reset =“”by =“”peer =“”>

时间:2017-06-15 09:15:36

标签: python urllib2 mechanize

我在Python 2.7中的脚本每分钟都会抓取一个网站,但有时会出错:

urlopen错误[Errno 54]通过对等方重置连接&gt;

我如何处理异常?我正在尝试这样的事情:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        print "there is a time-out" 
    pass
        print "There is no time-out, continue" 

1 个答案:

答案 0 :(得分:2)

您可以像这样处理异常:

from socket import error as SocketError
import errno    

try:
    urllib2.urlopen(request).read()
except SocketError, e:
     errorcode = e[0]
     if errorcode!=errno.ECONNREFUSED:
        print "There is a time-out"
        # Not the error we are looking for, re-raise
        raise e

您可以阅读Error Code