2022年 11月 13日

Python爬虫使用requests下载文件,实现下载大文件断点续传

1.下载小文件

如果是小文件,比如说普通图片,完全可以一次请求加载到内存,即最普通的get请求

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!??¤
QQ群:623406465

  1. import requests
  2. req = requests.get("http://www.test.com/xxxxx/test.jpg")
  3. with open(r"c:\test.jpg", "wb") as f:
  4. f.write(req.content)

2.下载大文件

如果是大文件,一次性加载可能会导致内存爆满,所以可以采取分块读写的方法,每次只读写一小块就可以了

  1. import requests
  2. req = requests.get("http://www.test.com/xxxxx/test.jpg", stream=True)
  3. with open(r"c:\test.jpg", "wb") as f:
  4. for chunk in req.iter_content(chunk_size=1024): # 每次加载1024字节
  5. f.write(chunk)

上面用到的是iter_content()方法读取文件块,还有一个iter_lines()方法,功能与前者差不多,不过源码注释的最后一行写着“This method is not reentrant safe”

3.下载改进

我们可以把稍微改进一下,实现断点续传功能,这样在下载大文件被中断的时候可以继续下载。为了方便使用,我们可以把代码封装成一个类

  1. import sys
  2. import requests
  3. import os
  4. class Downloader(object):
  5. def __init__(self, url, file_path):
  6. self.url = url
  7. self.file_path = file_path
  8. def start(self):
  9. res_length = requests.get(self.url, stream=True)
  10. total_size = int(res_length.headers['Content-Length'])
  11. print(res_length.headers)
  12. print(res_length)
  13. if os.path.exists(self.file_path):
  14. temp_size = os.path.getsize(self.file_path)
  15. print("当前:%d 字节, 总:%d 字节, 已下载:%2.2f%% " % (temp_size, total_size, 100 * temp_size / total_size))
  16. else:
  17. temp_size = 0
  18. print("总:%d 字节,开始下载..." % (total_size,))
  19. headers = {'Range': 'bytes=%d-' % temp_size,
  20. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0"}
  21. res_left = requests.get(self.url, stream=True, headers=headers)
  22. with open(self.file_path, "ab") as f:
  23. for chunk in res_left.iter_content(chunk_size=1024):
  24. temp_size += len(chunk)
  25. f.write(chunk)
  26. f.flush()
  27. done = int(50 * temp_size / total_size)
  28. sys.stdout.write("\r[%s%s] %d%%" % ('█' * done, ' ' * (50 - done), 100 * temp_size / total_size))
  29. sys.stdout.flush()
  30. if __name__ == '__main__':
  31. url = "https://vd2.bdstatic.com/mda-imt4u2h7u35k/xxxxxxx"
  32. path = "C:/test.mp4"
  33. downloader = Downloader(url, path)
  34. downloader.start()