使用Python下載網路檔案?


Python 提供了不同的模組,例如 urllibrequests 等,用於從網路下載檔案。我將使用Python的requests庫來高效地從URL下載檔案。

讓我們一步一步地看看如何使用requests庫從URL下載檔案:

1. 匯入模組

import requests

2. 獲取連結或URL

url = 'https://#/favicon.ico'
r = requests.get(url, allow_redirects=True)

3. 使用名稱儲存內容。

open('facebook.ico', 'wb').write(r.content)

將檔案儲存為facebook.ico。

示例

import requests


url = 'https://#/favicon.ico'
r = requests.get(url, allow_redirects=True)

open('facebook.ico', 'wb').write(r.content)

結果

我們可以看到檔案(圖示)已下載到我們的當前工作目錄。

但是我們可能需要從網路下載不同型別的檔案,例如影像、文字、影片等。所以讓我們首先獲取URL連結到的資料型別:

>>> r = requests.get(url, allow_redirects=True)
>>> print(r.headers.get('content-type'))
image/png

然而,有一種更聰明的方法,它涉及在實際下載檔案之前僅獲取URL的頭部資訊。這允許我們跳過下載那些不應下載的檔案。

>>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
False
>>> print(is_downloadable('https://#/favicon.ico'))
True

為了根據檔案大小限制下載,我們可以從content-length頭部資訊獲取檔案大小,然後根據我們的需求進行操作。

contentLength = header.get('content-length', None)
if contentLength and contentLength > 2e8: # 200 mb approx
return False

從URL獲取檔名

要獲取檔名,我們可以解析URL。下面是一個示例程式,它獲取反斜槓(/)後的最後一個字串。

url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
if url.find('/'):
print(url.rsplit('/', 1)[1]

以上將給出URL的檔名。但是,在許多情況下,例如http://url.com/download,URL中不存在檔名資訊。在這種情況下,我們需要獲取Content-Disposition頭部資訊,其中包含檔名資訊。

import requests
import re

def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = re.findall('filename=(.+)', cd)
if len(fname) == 0:
return None
return fname[0]


url = 'http://google.com/favicon.ico'
r = requests.get(url, allow_redirects=True)
filename = getFilename_fromCd(r.headers.get('content-disposition'))
open(filename, 'wb').write(r.content)

上述URL解析程式碼與上述程式結合使用,大多數情況下可以從Content-Disposition頭部資訊獲取檔名。

更新於:2023年8月22日

156K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告