Python urllib urlretrieve函數解析

來源:互聯網
上載者:User

Python urllib urlretrieve函數解析

Python urllib urlretrieve函數解析

利用urllib.request.urlretrieve函數下載檔案

urlretrieve(url, filename=None, reporthook=None, data=None)

參數 finename 指定了儲存本地路徑(如果參數未指定,urllib會產生一個臨時檔案儲存資料。)

參數 reporthook 是一個回呼函數,當串連上伺服器、以及相應的資料區塊傳輸完畢時會觸發該回調,我們可以利用這個回呼函數來顯示當前的下載進度。

參數 data 指 post 到伺服器的資料,該方法返回一個包含兩個元素的(filename, headers)元組,filename 表示儲存到本地的路徑,header 表示伺服器的回應標頭。

下面通過例子來示範一下這個方法的使用,這個例子將一張圖片抓取到本地,儲存在此檔案夾中,同時顯示下載的進度。

from six.moves import urllib


def Schedule(a, b, c):
    """
    a:已經下載的資料區塊
    b:資料區塊的大小
    c:遠程檔案的大小
    """
    per = 100.0*float(a*b)/float(c)
    if per > 100:
        per = 100
    print("a", a)
    print("b", b)
    print("c", c)
    print('{:.2f}%'.format(per))

url = 'https://avatars1.githubusercontent.com/u/14261323?s=400&u=150449ce27748c3b23b5175f8c8342c918ae6aa8&v=4'
local = 'mylogo.png'
filename, _ = urllib.request.urlretrieve(url, local, Schedule)
# ('mylogo.png', <http.client.HTTPMessage object at 0x000001FD6491D6D8>)
print(filename)
# mylogo.png

# a 0
# b 8192
# c 38225
# 0.00%
# a 1
# b 8192
# c 38225
# 21.43%
# a 2
# b 8192
# c 38225
# 42.86%
# a 3
# b 8192
# c 38225
# 64.29%
# a 4
# b 8192
# c 38225
# 85.72%
# a 5
# b 8192
# c 38225
# 100.00%

本文永久更新連結地址:https://www.bkjia.com/Linux/2018-02/150992.htm

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.