北京列举网 > 教育培训 > 电脑/网络 > 拉勾教育Python爬虫使用requests下载文件
北京
[切换城市]

拉勾教育Python爬虫使用requests下载文件

更新时间:2020-10-20 14:04:52 浏览次数:87次
区域: 北京 > 海淀 > 中关村
类别:软件工程师培训
地址:创业大街
下载小文件
如果是小文件,比如说普通图片,完全可以一次请求加载到内存,即普通的get请求,拉勾IT课小编为大家分析
很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!

import requests

req = requests.get("http://www.tes***/xxxxx/test.jpg")
with open(r"c:test.jpg", "wb") as f:
  f.write(re***ntent)


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

import requests

req = requests.get("http://www.tes***/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.bds***/mda-imt4u2h7u35k/xxxxxxx"
  path = "C:/test.mp4"
  downloader = Downloader(url, path)
  downloader.start()

北京电脑/网络相关信息
4月23日
办公软件培训
平谷-平谷城区
4月19日
办公软件培训
平谷-平谷城区
4月11日
办公软件培训
平谷-平谷城区
4月9日
办公软件培训
平谷-平谷城区
4月7日
4月1日
注册时间:2020年08月17日
UID:706396
---------- 认证信息 ----------
手机已认证
查看用户主页