簡體   English   中英

請求無法獲取 pdf URL 並下載它

[英]Requests is unable to get a pdf URL and download it

對於我的工作,我們需要下載很多產品 pdf。 這導致我不想一遍又一遍地點擊一長串網址。 對於某些人來說,我可以使用下面的代碼來下載 pdf,但對於其他人(如包含的那個),當我要求它獲取 url 時,請求似乎陷入了某種無限循環。

我嘗試了在其他地方看到的不同參數和不同提示,但沒有任何效果。 我是編碼和 python 的新手,所以我可能在這里遺漏了一些明顯的東西。 任何幫助和解釋將不勝感激。 謝謝!

import requests # to get image from the web
import shutil # to save it locally

url = "https://www.us.kohler.com/webassets/kpna/catalog/pdf/en/K-10411_spec_US-CA_Kohler_en.pdf"
filename = 'TEST-Image.pdf'

r = requests.get(url, stream = True)

if r.status_code == 200:

    r.raw.decode_content = True

with open(filename,'wb') as f:
    shutil.copyfileobj(r.raw, f)
    
    print('PDF sucessfully Downloaded: ',filename)
else:
    print('PDF Couldn\'t be retrieved')

這里的問題,至少對於提供的特定鏈接來說,是科勒方面的某些東西不喜歡沒有在標頭中設置user-agent請求。 這要么是錯誤,要么是故意的。 這實際上可能是為了防止人們完全按照您正在做的事情進行——大量下載他們的手冊。 無論如何,解決方案很簡單。

將您的請求調用修改為如下所示:

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
r = requests.get(url, stream = True, headers = headers)

請注意,提供的實際user-agent字符串只是 Windows 10 上 Chrome 的標准字符串。您可能可以使用任何您想要的user-agent字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM