1.下载小文件
如果是小文件,比如说普通图片,完全可以一次请求加载到内存,即最普通的get请求
很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!??¤
QQ群:623406465
-
- import requests
-
- req = requests.get("http://www.test.com/xxxxx/test.jpg")
- with open(r"c:\test.jpg", "wb") as f:
- f.write(req.content)
-
2.下载大文件
如果是大文件,一次性加载可能会导致内存爆满,所以可以采取分块读写的方法,每次只读写一小块就可以了
-
- import requests
-
- req = requests.get("http://www.test.com/xxxxx/test.jpg", stream=True)
- with open(r"c:\test.jpg", "wb") as f:
- for chunk in req.iter_content(chunk_size=1024): # 每次加载1024字节
- f.write(chunk)
-
上面用到的是iter_content()方法读取文件块,还有一个iter_lines()方法,功能与前者差不多,不过源码注释的最后一行写着“This method is not reentrant safe”
3.下载改进
我们可以把稍微改进一下,实现断点续传功能,这样在下载大文件被中断的时候可以继续下载。为了方便使用,我们可以把代码封装成一个类
- import sys
- import requests
- import os
-
-
- class Downloader(object):
- def __init__(self, url, file_path):
- self.url = url
- self.file_path = file_path
-
- def start(self):
- res_length = requests.get(self.url, stream=True)
- total_size = int(res_length.headers['Content-Length'])
- print(res_length.headers)
- print(res_length)
- if os.path.exists(self.file_path):
- temp_size = os.path.getsize(self.file_path)
- print("当前:%d 字节, 总:%d 字节, 已下载:%2.2f%% " % (temp_size, total_size, 100 * temp_size / total_size))
- else:
- temp_size = 0
- print("总:%d 字节,开始下载..." % (total_size,))
-
- headers = {'Range': 'bytes=%d-' % temp_size,
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0"}
- res_left = requests.get(self.url, stream=True, headers=headers)
-
- with open(self.file_path, "ab") as f:
- for chunk in res_left.iter_content(chunk_size=1024):
- temp_size += len(chunk)
- f.write(chunk)
- f.flush()
-
- done = int(50 * temp_size / total_size)
- sys.stdout.write("\r[%s%s] %d%%" % ('█' * done, ' ' * (50 - done), 100 * temp_size / total_size))
- sys.stdout.flush()
-
-
- if __name__ == '__main__':
- url = "https://vd2.bdstatic.com/mda-imt4u2h7u35k/xxxxxxx"
- path = "C:/test.mp4"
- downloader = Downloader(url, path)
- downloader.start()