简易的Python版HTTP下载

爱必应

闲来无事写了一个简易的Python3 HTTP下载
理论上能下载所有浏览器能下载的东西,如果处理的好,几乎都可以{:1_918:}
没有什么技术含量,直接给出源代码

[Python] 纯文本查看 复制代码

import osimport timeimport requestsheaders = { "Proxy-Connection": "keep-alive", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",}proxies = { "http": "http://127.0.0.1:1080"}def download_file(filename, url): res = requests.post(url, stream=True, headers=headers) file_length = float(res.headers['content-length']) print('响应文件大小:' + str(file_length)) with open(filename, mode='wb') as file: count = 0 count_tmp = 0 times = time.time() for chunk in res.iter_content(chunk_size=512): if chunk: file.write(chunk) count += len(chunk) if time.time() - times > 2: p = count / file_length * 100 speed = (count - count_tmp) / 1024 / 1024 / 2 count_tmp = count print(filename + ': ' + format_float(p) + '%' + ' Speed: ' + format_float(speed) + 'M/S') times = time.time() if float(os.path.getsize(filename)) == file_length: print(filename + ',下载成功') else: print(filename + '下载失败') exit(0)def format_float(num): return '{:.2f}'.format(num)if __name__ == '__main__': urls = input('请输入下载链接:').strip() name = 'files' download_file(name, urls)

对你有帮助的,麻烦给个免费点赞哦!
如有侵权请联系我。

原文链接:,转发请注明来源!

发表评论