代码之家  ›  专栏  ›  技术社区  ›  Jakub Bláha

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

  •  5
  • Jakub Bláha  · 技术社区  · 7 年前

    我有一行代码: urllib.request.urlretrieve('http://lolupdater.com/downloads/LPB.exe', 'LPBtest.exe') urllib.error.HTTPError: HTTP Error 403: Forbidden .

    1 回复  |  直到 6 年前
        1
  •  5
  •   andrew    7 年前

    这看起来是一个实际的HTTP 403: Forbidden urllib 当遇到HTTP状态代码(已记录)时引发异常 here ). 403 通常的意思是:“服务器理解了请求,但拒绝满足它。”您需要添加HTTP头来标识您自己,并避免 错误,文档 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)
    

    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)