Most people recommend using requests if it is available, and the requests documentation recommends this for downloading and saving raw data from a url:
Using
Response.iter_content
will handle a lot of what you would otherwise have to handle when usingResponse.raw
directly. When streaming a download, the above is the preferred and recommended way to retrieve the content. Note thatchunk_size
can be freely adjusted to a number that may better fit your use cases.
Response.iter_content
will automatically decode the gzip and deflate transfer-encodings.Response.raw
is a raw stream of bytes – it does not transform the response content. If you really need access to the bytes as they were returned, useResponse.raw
.
Example Code
import requests
filename = 'd:/master.zip'
url = 'https://github.com/requests/requests-docs-cn/archive/refs/heads/master.zip'
response = requests.get(url, stream=True)
with open(filename, 'wb') as fd:
for chunk in response.iter_content(chunk_size=128):
fd.write(chunk)
or you can use urllib.request.urlopen
import urllib.request
filename = 'd:/master.zip'
url = 'https://github.com/requests/requests-docs-cn/archive/refs/heads/master.zip'
with urllib.request.urlopen(url) as dl_file:
with open(filename, 'wb') as out_file:
out_file.write(dl_file.read())
推荐文章: