我正在嘗試從 URL 下載檔案:
https://www.cmegroup.com/content/dam/cmegroup/notices/clearing/2020/08/Chadv20-239.pdf
我嘗試使用 python requests 庫,但請求只是超時。我嘗試將瀏覽器中的“用戶代理”指定為標題,但它仍然超時,包括當我將瀏覽器中的每個標題復制到我的 python 腳本中時。我嘗試設定allow_redirects=True,這沒有幫助。我也試過 wget 和 curl,除了實際打開瀏覽器、訪問 URL 和下載檔案之外,一切都失敗了。
我想知道我的瀏覽器中的請求與我將標頭設定為與瀏覽器中的相匹配的 python 請求之間的實際區別是什么 - 有什么辦法可以使用 python 下載這個檔案?
代碼片段:
import requests
requests.get("https://www.cmegroup.com/content/dam/cmegroup/notices/clearing/2020/08/Chadv20-239.pdf") # hangs
uj5u.com熱心網友回復:
檢查這個,它對我有用。
import requests
headers = {
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36'}
response = requests.get(
"https://www.cmegroup.com/content/dam/cmegroup/notices/clearing/2020/08/Chadv20-239.pdf", headers=headers)
pdf = open("Chadv20-239.pdf", 'wb')
pdf.write(response.content)
pdf.close()
uj5u.com熱心網友回復:
如果沒有一些代碼片段,很難理解可能會出現什么問題。檔案是如何下載的?您是否正在獲取原始回應內容并將其保存為 pdf?官方檔案(https://docs.python-requests.org/en/latest/user/quickstart/#raw-response-content)建議使用基于塊的方法來保存流式/原始內容。你嘗試過這種方法嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/385062.html
