处理ConnectionResetError

时间:2016-09-02 08:24:43

标签: python urllib

我有一个关于在Python3中处理ConnectionResetError的问题。这通常发生在我使用urllib.request.Request函数时。如果遇到这样的错误,我想知道是否可以重做请求。例如

def get_html(url):
    try:
        request = Request(url)
        response = urlopen(request)
        html = response.read()
    except ConectionReserError as e:
        get_html(url)

1 个答案:

答案 0 :(得分:1)

这实际上取决于服务器,但您可以执行以下操作:

def get_html(url, retry_count=0):
    try:
        request = Request(url)
        response = urlopen(request)
        html = response.read()
    except ConectionResetError as e:
        if retry_count == MAX_RETRIES:
            raise e
        time.sleep(for_some_time)
        get_html(url, retry_count + 1)

另见Python handling socket.error: [Errno 104] Connection reset by peer