讨论数量: 1

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 using Response.raw directly. When streaming a download, the above is the preferred and recommended way to retrieve the content. Note that chunk_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, use Response.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):

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:
1周前 评论