强制从URL下载图像的最长时间

2024-04-29 05:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现一种方法,尝试从url下载一些图像。为此,我使用了请求库。我的代码示例如下:

while attempts < nmr_attempts:
        try:
            attempts += 1
            response = requests.get(self.basis_url, params=query_params, timeout=response_timeout)
        except Exception as e:
            pass

每次尝试发出请求的时间不能超过“响应超时”。然而,似乎timeout变量没有做任何事情,因为它不尊重我给出的时间

如何限制response.get()调用的最大阻塞时间。 提前谢谢


Tags: 方法代码图像url示例getresponse时间
1条回答
网友
1楼 · 发布于 2024-04-29 05:33:39

你能试试下面的方法(去掉try,除了block)看看是否有帮助吗Exception可能正在抑制请求的异常。get抛出的异常

while attempts < nmr_attempts:
    response = requests.get(self.basis_url, params=query_params, timeout=response_timeout)

或者使用原始代码,您可以捕获请求。异常。ReadTimeout异常。例如:

while attempts < nmr_attempts:
    try:
        attempts += 1
        response = requests.get(self.basis_url, params=query_params, timeout=response_timeout)
    except requests.exceptions.ReadTimeout as e:
        do_something()

相关问题 更多 >