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