一、概述
使用python3寫了一個擷取某網站檔案的小腳本,使用了requests子產品的get方法得到内容,然後通過檔案讀寫的方式儲存到硬碟
同時需要實作下載下傳進度的顯示
二、代碼實作
安裝子產品
pip3 install requests tqdm
複制
test.py 完整代碼如下:
#!/usr/bin/env python3
# coding: utf-8
import os
from urllib.request import urlopen
import requests
from tqdm import tqdm
def download_from_url(url, dst):
"""
@param: url to download file
@param: dst place to put the file
:return: bool
"""
# 擷取檔案長度
try:
file_size = int(urlopen(url).info().get('Content-Length', -1))
except Exception as e:
print(e)
print("錯誤,通路url: %s 異常" % url)
return False
# 檔案大小
if os.path.exists(dst):
first_byte = os.path.getsize(dst)
else:
first_byte = 0
if first_byte >= file_size:
return file_size
header = {"Range": "bytes=%s-%s" % (first_byte, file_size)}
pbar = tqdm(
total=file_size, initial=first_byte,
unit='B', unit_scale=True, desc=url.split('/')[-1])
# 通路url進行下載下傳
req = requests.get(url, headers=header, stream=True)
try:
with(open(dst, 'ab')) as f:
for chunk in req.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
pbar.update(1024)
except Exception as e:
print(e)
return False
pbar.close()
return True
if __name__ == '__main__':
url = "https://dl.360safe.com/360/inst.exe"
download_from_url(url, "inst.exe")
複制
效果如下:

本文參考連結:
https://www.zhihu.com/question/41132103/answer/279584095