【问题标题】:Python howto exception handle <urlopen error [Errno 54] Connection reset by peer>Python howto 异常处理 <urlopen 错误 [Errno 54] Connection reset by peer>
【发布时间】:2017-06-15 09:15:36
【问题描述】:

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

urlopen 错误 [Errno 54] Connection reset by peer>

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

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" 

【问题讨论】:

    标签: python urllib2 mechanize


    【解决方案1】:

    你可以这样处理异常:

    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

    【讨论】:

    • 我已将您的代码导入到我的脚本中,半小时后我收到错误消息:除了 SocketError,e: NameError: name 'SocketError' is not defined。
    • errno上方添加这一行from socket import error as SocketError
    • 我替换了 except SocketError, e: in except socket.error as e: 如果它有效我会试试这个。感谢您的帮助
    • 哦,我忘记了你的代码行!好的,我会再试一次。
    • 如果您的问题仍然没有解决,试试这个Question
    猜你喜欢
    • 2022-11-02
    • 2019-11-04
    • 2022-12-06
    • 1970-01-01
    • 2021-03-07
    • 2012-01-18
    • 2016-06-21
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多