python - 处理 ConnectionResetError

标签 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)

最佳答案

这真的取决于服务器,但你可以这样做:

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

关于python - 处理 ConnectionResetError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39287669/

相关文章:

python - 在 Bokeh 高级图表中使用 LinearColorMapper

rest - 如何让客户端接受服务器的SSL证书

python - urllib 是否加密身份验证数据?

python - 在Python中按日期从http下载多个XLS文件

python - 请求 response.iter_content() 得到不完整的文件(1024MB 而不是 1.5GB)?

python - Urllib 算作网页点击吗?

用于简单问题的 Python 正则表达式

python - 如何向 lxml 元素添加属性

python - 如何遍历 python 列表,并在继续该过程之前停止加载下一个 URL?

python - 将元素插入到 numpy 数组中,以便最小间距是任意的