2017-05-07 66 views
3

當使用urllib.request.urlretrieve時,我想知道是否有方法查看控制檯中打印的下載狀態以及文件大小等信息?如何查看下載過程?

下面是我測試的代碼:

#!/usr/bin/env python3.5.2 

import urllib.request 
import os 


# make sure to change the directory before you test the code 
directory = r'C:\Users\SalahGfx\Desktop\Downloads' 

url = 'https://upload.wikimedia.org/wikipedia/en/d/d8/C4D_Logo.png' 

def get_name_path(): 
    image_name = url.split('/')[-1] 
    return os.path.join(directory, image_name) 

urllib.request.urlretrieve(url, get_name_path()) 

print('The Image has been downloaded!') 

回答

3

沒有內置任何你將不得不自己編寫。幸運的是,這並不困難。您只需從頭文件中讀取內容的長度,然後通過塊讀取響應。下面的代碼

import urllib2, sys 

def chunk_report(bytes_so_far, chunk_size, total_size): 
    percent = float(bytes_so_far)/total_size 
    percent = round(percent*100, 2) 
    sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" % 
        (bytes_so_far, total_size, percent)) 

    if bytes_so_far >= total_size: 
     sys.stdout.write('\n') 

def chunk_read(response, chunk_size=8192, report_hook=None): 
    total_size = response.info().getheader('Content-Length').strip() 
    total_size = int(total_size) 
    bytes_so_far = 0 

    while 1: 
     chunk = response.read(chunk_size) 
     bytes_so_far += len(chunk) 

     if not chunk: 
      break 

     if report_hook: 
      report_hook(bytes_so_far, chunk_size, total_size) 

    return bytes_so_far 

def get_name_path(): 
    image_name = url.split('/')[-1] 
    return os.path.join(directory, image_name) 

# make sure to change the directory before you test the code 
directory = r'C:\Users\SalahGfx\Desktop\Downloads' 

url = 'https://upload.wikimedia.org/wikipedia/en/d/d8/C4D_Logo.png' 

response = urllib.request.urlopen(url, get_name_path()) 
chunk_read(response, report_hook=chunk_report) 

要注意,我用urllib.request.urlopen因爲urllib2.request.retrieve被認爲是legacy和即將棄用這一點很重要。

+0

感謝您的良好回答我現在明白了做這件事背後的邏輯,但是我知道urlopen只帶有沒有文件名的url,所以它是取代urlretrieve的唯一方法嗎? – SalahGfx