我試圖自動下載一堆 pdf。其中一個網址如下
https://www.unpri.org/download?ac=4195
我正在使用以下代碼從此 URL 獲取標頭
import requests
h = requests.head(url, allow_redirects=True)
header = h.headers
print(header)
這些是標題
{'Cache-Control': 'no-cache', 'Connection': 'close', 'Content-Type': 'text/html'}
沒有內容處置或任何其他可以給我檔案名的東西。但是,當我在瀏覽器中打開它并右鍵單擊 --> 另存為時,我可以選擇使用其原始名稱保存(下面的螢屏截圖)
截屏
有什么辦法可以用 python 獲取這個檔案名嗎?
uj5u.com熱心網友回復:
只需添加正確User-Agent并使用回應頭來獲取檔案名。
就是這樣:
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0",
}
r = requests.get("https://www.unpri.org/download?ac=4195", headers=headers)
print(r.headers["Content-disposition"].split("=", -1)[-1])
輸出:
PRI_Investor_guide_on_agricultural_supply_chain.pdf
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414631.html
標籤:
