• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python 下载文件的多种方法汇总

python 搞代码 4年前 (2022-01-09) 19次浏览 已收录 0个评论

本文档介绍了 Python 下载文件的各种方式,从下载简单的小文件到用断点续传的方式下载大文件。

Requests

使用 Requests 模块的 get 方法从一个 url 上下载文件,在 python 爬虫中经常使用它下载简单的网页内容

import requests

# 图片来自bing.com
url = 'https://cn.bing.com/th?id=OHR.DerwentIsle_EN-CN8738104578_400x240.jpg'

def requests_download():

  content = requests.get(url).content

  with open('pic_requests.jpg', 'wb') as file:
    file.write(content)

urllib

使用 python 内置的 urllib 模块的 urlretrieve 方法直接将 url 请求保存成文件

from urllib import request

# 图片来自bing.com
url = 'https://cn.bing.com/th?id=OHR.DerwentIsle_EN-CN8738104578_400x240.jpg'

def urllib_download():
  request.urlretrieve(url, 'pic_urllib.jpg')

urllib3

urllib3 是一个用于 本文来源gao@daima#com搞(%代@#码@网&Http 客户端的 Python 模块,它使用连接池对网络进行请求访问

def urllib3_download():
  # 创建一个连接池
  poolManager = urllib3.PoolManager()

  resp = poolManager.request('GET', url)

  with open("pic_urllib3.jpg", "wb") as file:
    file.write(resp.data)

  resp.release_conn()

wget

在 Linux 系统中有 wget 命令,可以方便的下载网上的资源,Python 中也有相应的 wget 模块。使用 pip install 命令安装

import wget

# 图片来自bing.com
url = 'https://cn.bing.com/th?id=OHR.DerwentIsle_EN-CN8738104578_400x240.jpg'

def wget_download():
  wget.download(url, out='pic_wget.jpg')

也可以直接在命令行中使用 wget 命令

python -m wget https://cn.bing.com/th?id=OHR.DerwentIsle_EN-CN8738104578_400x240.jpg

分块下载大文件

在需要下载的文件非常大,电脑的内存空间完全不够用的情况下,可以使用 requests 模块的流模式,默认情况下 stream 参数为 False, 文件过大会导致内存不足。stream 参数为 True 的时候 requests 并不会立刻开始下载,只有在调用 iter_content 或者 iter_lines 遍历内容时下载

iter_content:一块一块的遍历要下载的内容 iter_lines:一行一行的遍历要下载的内容

import requests

def steam_download():
  # vscode 客户端
  url = 'https://vscode.cdn.azure.cn/stable/e5a624b788d92b8d34d1392e4c4d9789406efe8f/VSCodeUserSetup-x64-1.51.1.exe'

  with requests.get(url, stream=True) as r:
    with open('vscode.exe', 'wb') as flie:
      # chunk_size 指定写入大小每次写入 1024 * 1024 bytes
      for chunk in r.iter_content(chunk_size=1024*1024):
        if chunk:
          flie.write(chunk)

进度条

在下载大文件的时候加上进度条美化下载界面,可以实时知道下载的网络速度和已经下载的文件大小,这里使用 tqdm 模块作为进度条显示,可以使用 pip install tqdm 安装

from tqdm import tqdm

def tqdm_download():

  url = 'https://vscode.cdn.azure.cn/stable/e5a624b788d92b8d34d1392e4c4d9789406efe8f/VSCodeUserSetup-x64-1.51.1.exe'

  resp = requests.get(url, stream=True)

  # 获取文件大小
  file_size = int(resp.headers['content-length'])
  
  with tqdm(total=file_size, unit='B', unit_scale=True, unit_divisor=1024, ascii=True, desc='vscode.exe') as bar:
    with requests.get(url, stream=True) as r:
      with open('vscode.exe', 'wb') as fp:
        for chunk in r.iter_content(chunk_size=512):
          if chunk:
            fp.write(chunk)
            bar.update(len(chunk))

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python 下载文件的多种方法汇总

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址