標籤:while 下載 res .net code 實現 檔案 str under
Requests庫,高度封裝的http庫
import requestsurl = ‘http://down.sandai.net/thunder9/Thunder9.0.18.448.exe‘filename = url.split(‘/‘)[-1] #擷取檔案名稱r = requests.get(url,stream = True)with open(filename,‘wb‘) as f: p = 0 #下載計數器 chunk_size = 4096 #塊大小 try: while True: for data in r.iter_content(chunk_size): p += f.write(data) print(‘%d‘ % (p)) except Exception as e: print(e) finally: print(‘下載完畢!‘)
urllib庫,操作上能比Requests靈活一點,沒有特殊需求的話基本沒什麼差別
import urllib.requesturl = ‘http://down.sandai.net/thunder9/Thunder9.0.18.448.exe‘resp = urllib.request.urlopen(url)filename = url.split(‘/‘)[-1]with open(filename,‘wb‘) as f: p = 0 #下載計數 buffsize = 4096 #塊大小 try: while True: buff = resp.read(buffsize) if not buff: #buff為空白,即下載完畢,結束迴圈 break p += f.write(buff) print(‘%d‘ % p) except Exception as e: print(e) finally: print(‘下載完畢!‘)
還有個一句話的
import urlliburllib.urlretrieve(url, ‘test.jpg’)
python 實現檔案檔案