HTTP错误403:使用urllib下载文件时禁止

时间:2017-07-27 18:09:40

标签: python-3.x file download urllib

我有这行代码:urllib.request.urlretrieve('http://lolupdater.com/downloads/LPB.exe', 'LPBtest.exe'),但是当我运行它时,它会抛出错误urllib.error.HTTPError: HTTP Error 403: Forbidden

1 个答案:

答案 0 :(得分:2)

这看起来是一个实际的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)
相关问题