Python script 下载文件

  1. 简单直白的版本
import requests 

def download_file(url):
    r = requests.get(url) 
    with open("test.zip", "wb") as f:
        f.write(r.content)
  1. 大文件的下载
import requests 

def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
    return local_filename
  1. 更 robust 的版本
    可以看到这里,这篇文章作者基本上考虑到了下载中会遇到的各种情况,源代码在这里。
添加新评论