首页 > 编程语言 > python 下载文件的几种方法汇总
2021
01-08

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

前言

  使用脚本进行下载的需求很常见,可以是常规文件、web页面、Amazon S3和其他资源。Python 提供了很多模块从 web 下载文件。下面介绍

一、使用 requests

  requests 模块是模仿网页请求的形式从一个URL下载文件

示例代码:

import requests

url = 'xxxxxxxx' # 目标下载链接
r = requests.get(url) # 发送请求
# 保存
with open ('r.txt', 'rb') as f:
 f.write(r.content)
 f.close

爬虫请求库——requests的使用

二、使用 wget

安装 wget 库

pip install wget

示例代码

import wget

url = 'https://pic.cnblogs.com/avatar/1197773/20170712160655.png' # 目标路由,下载的资源是图片
path = 'D:/x.png' # 保存的路径
wget.download(url, path) # 下载

三、下载重定向资源

  有些 URL 会被重定向到另一个 URL,后者是真正的下载链接。很多软件的下载其实都是这样的形式。URL看起来如下

https://readthedocs.org/projects/python-guide/downloads/pdf/latest

  重定向的 URL 也可以用 requests 库进行下载,只需加一个参数就可以

import requests

url = 'https://readthedocs.org/projects/python-guide/downloads/pdf/latest'

# allow_redirect参数True表示允许重定向
r = requests.get(url, allow_redirect=True)
with open('r.txt', 'wb') as f:
 f.write(r)
 f.close()

四、大文件分块下载

  有些文件非常的大,如果我们直接下载,可能会因为事件原因或者网络原因造成下载失败,这时候我可以使用分块下载的形式进行下载。

  requests 支持分块下载,只需要将 stream 设为True 即可

import requests

url = 'https://readthedocs.org/projects/python-guide/downloads/pdf/latest'

# stream参数True表示分块下载
r = requests.get(url, stream=True)
with open('r.txt', 'wb') as f:
 for ch in r:
 f.write(r)
 f.close()

五、并行下载

  多线程、多进程并发下载,大大提高下载速度

import requests
from multiprocessing.poll import Pool

# 定义下载函数
def url_response(url):
 path, url = url
 r = requests.get(url, stream=True)
 with open(path, 'wb') as f:
 for ch in r:
  f.write(ch)
 f.close()

urls = ['aaa', 'bbb', 'ccc'] # 假设有好多个下载链接

# 排队下载的方式
for x in urls:
 url_response(x)

# 并行下载的方式
ThreadPool(3).imap_unordered(url_response, urls)

六、下载中加入进度条

  使用进度条更直观的查看下载进度,这里使用 clint 模块实现进度条功能

pip install clint

下载

import requests
from clint.textui import progess

url = 'xxxxxxxxxxx'
r = requests.get(url, stream=True)
with open('x.txt', 'wb') as f
 total_length = int(r.headers.get('content-length'))
 for ch in progress.bar(r.iter_content(chunk_size=2391975, expected)size=(total_length/1024)+1)):
 if ch:
  f.write(ch)
 f.close()

其他使用进度条的案例:Python 实现进度条的六种方式

七、使用 urllib 模块下载

  urllib库是Python的标准库,因此不需要安装它。

下载代码

urllib.request.urlretrieve(URL, PATH)

八、通过代理下载

  因为一些众所周知的原因我们下载国外的资源会非常的慢,这时候可以使用代理的方式进行下载

requests 模块使用代理

import requests

# 定义代理,假设本机上有个梯子的服务,代理端口是2258
proxy = {'http': 'http://127.0.0.1:2258'} 

url = 'xxxxxx'
r = requests.get(url, proxies=proxy )
.......

urllib 模块使用代理

import urllib.request

url = 'xxxxxxxxxx'
proxy = urllib.request.ProxyHandler({'http': '127.0.0.1'})
open_proxy = urllib.request.build_opener(proxy ) # 打开代理
urllib.request.urlretrieve(url)

九、使用 urllib3

  urllib3 是 urllib 模块的改进版本。使用pip下载并安装

pip install urllib3

以上就是python 下载文件的几种方法汇总的详细内容,更多关于python 下载文件的资料请关注自学编程网其它相关文章!

编程技巧