Mon*_*oya 3 python http urllib urllib2 urllib3
我正在使用 urllib3 爬网。示例代码:
from urllib3 import PoolManager
pool = PoolManager()
response = pool.request("GET", url)
Run Code Online (Sandbox Code Playgroud)
问题是我可能会偶然发现 url 是一个非常大的文件的下载,我并不介意下载它。
我发现了这个问题 - Link - 它建议使用urllib
and urlopen
。我不想两次联系服务器。
我想将文件大小限制为 25MB。有没有办法做到这一点urllib3
?
如果服务器提供Content-Length
标头,那么您可以使用它来确定是否要继续下载正文的其余部分。如果服务器不提供标头,则您需要流式传输响应,直到您决定不再继续。
为此,您需要确保没有预加载完整的响应。
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()
Run Code Online (Sandbox Code Playgroud)