1
我有這行代碼:urllib.request.urlretrieve('http://lolupdater.com/downloads/LPB.exe', 'LPBtest.exe')
,但是當我運行它時,它會拋出錯誤urllib.error.HTTPError: HTTP Error 403: Forbidden
。請幫幫我。謝謝。HTTP錯誤403:使用urllib下載文件時禁止
我有這行代碼:urllib.request.urlretrieve('http://lolupdater.com/downloads/LPB.exe', 'LPBtest.exe')
,但是當我運行它時,它會拋出錯誤urllib.error.HTTPError: HTTP Error 403: Forbidden
。請幫幫我。謝謝。HTTP錯誤403:使用urllib下載文件時禁止
這看起來是一個實際的HTTP 403: Forbidden
錯誤。 Python urllib
遇到HTTP狀態代碼時引發異常(記錄爲here)。一般意義上的403
表示:「服務器理解請求,但拒絕履行它。」您需要添加HTTP標頭以標識自己並避免出現403
錯誤,文檔位於Python urllib headers。下面是使用urlopen
一個例子:
import urllib.request
req = urllib.request.Request('http://lolupdater.com/downloads/LPB.exe', headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req)
使用Python 3 urllib.urlretrieve()
是considered legacy。我會爲此推薦Python Requests,下面是一個工作示例:
import requests
url = 'http://lolupdater.com/downloads/LPB.exe'
r = requests.get(url)
with open('LPBtest.exe', 'wb') as outfile:
outfile.write(r.content)
但如何保存數據比如果我有一個可執行文件? –
@JakubBláha我更新了我的答案。它看起來像'urllib.urlretrieve()'不允許你設置標題。我會推薦使用Python Requests,它絕對是更接受的方式來做你想做的事情,希望它有幫助。 – andrew