前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 用 requests 2

Python3 用 requests 2

作者头像
py3study
发布2020-01-03 11:08:47
3670
发布2020-01-03 11:08:47
举报
文章被收录于专栏:python3

【环境】

  • OS:Windows 10 x64
  • Python:3.6.5 x64
  • requests:2.18.4

【代码】

代码语言:javascript
复制
# encoding: utf-8
# author: walker
# date: 2018-06-11
# summary: 使用 requests 下载大文件

import time
import requests

# 下载一个大文件
def DownOneFile(srcUrl, localFile):
    print('%s\n --->>>\n  %s' % (srcUrl, localFile))
    
    startTime = time.time()
    with requests.get(srcUrl, stream=True) as r:
        contentLength = int(r.headers['content-length'])
        line = 'content-length: %dB/ %.2fKB/ %.2fMB'
        line = line % (contentLength, contentLength/1024, contentLength/1024/1024)
        print(line)
        downSize = 0
        with open(localFile, 'wb') as f:
            for chunk in r.iter_content(8192):
                if chunk:
                    f.write(chunk)
                downSize += len(chunk)
                line = '%d KB/s - %.2f MB, 共 %.2f MB'
                line = line % (downSize/1024/(time.time()-startTime), downSize/1024/1024, contentLength/1024/1024)
                print(line, end='\r')
                if downSize >= contentLength:
                    break
        timeCost = time.time() - startTime
        line = '共耗时: %.2f s, 平均速度: %.2f KB/s'
        line = line % (timeCost, downSize/1024/timeCost)
        print(line)

if __name__ == '__main__':
    srcUrl = r'http://cachefly.cachefly.net/100mb.test'
    localFile = r'D:\Python3Project\test\out\out.test'
    DownOneFile(srcUrl, localFile)

【效果图】

QQ图片20180611145446.png
QQ图片20180611145446.png
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档