python requests先获取请求资源的大小

# 关键代码 stream = True 参数,以流的方式读取
# 执行代码 直接给出文件大小
url = 'url自己找吧'
re = requests.get(url,stream=True)
print(re.headers.get('Content-Length'))




主要用在下载大文件

def request_url(url, headers, file_path):
    m = hashlib.md5()
    start_time = time.time()
    with open(file_path, 'wb') as code:
        with closing(requests.get(url, headers=headers, timeout=3, stream=True)) as res:
            file_size_str = res.headers.get('Content-Length')
            if int(file_size_str) > 300000000:
                return 'no', 'no', 'no'
            for chunk in res.iter_content(chunk_size=10240):
                if time.time() - start_time > 3:
                    return 'no', 'no', 'no'
                start_time = time.time()
                code.write(chunk)
                m.update(chunk)
    return m.hexdigest(), file_path, file_size_str

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值