Python | HTTP - 如何在下载前检查文件大小

Python | HTTP - How to check file size before downloading it

我正在使用 urllib3 抓取网络。示例代码:

from urllib3 import PoolManager

pool = PoolManager()
response = pool.request("GET", url)

问题是我可能会偶然发现 url 这是一个非常大的文件的下载,我并没有兴趣下载它。

我发现了这个问题 - Link - 它建议使用 urlliburlopen。我不想联系服务器两次。

我想将文件大小限制为 25MB。 我可以用 urllib3 做到这一点吗?

如果服务器提供 Content-Length header,那么您可以使用它来确定是否要继续下载 body 的其余部分。如果服务器不提供 header,则您需要流式传输响应,直到您决定不再继续。

为此,您需要确保自己 not preloading the full response

from urllib3 import PoolManager

pool = PoolManager()
response = pool.request("GET", url, preload_content=False)

# Maximum amount we want to read  
max_bytes = 1000000

content_bytes = response.headers.get("Content-Length")
if content_bytes and int(content_bytes) < max_bytes:
    # Expected body is smaller than our maximum, read the whole thing
    data = response.read()
    # Do something with data
    ...
elif content_bytes is None:
    # Alternatively, stream until we hit our limit
    amount_read = 0
    for chunk in r.stream():
        amount_read += len(chunk)
        # Save chunk
        ...
        if amount_read > max_bytes:
            break

# Release the connection back into the pool
response.release_conn()