【问题标题】:HTTP Error 403: Forbidden with urlretrieveHTTP 错误 403:使用 urlretrieve 禁止
【发布时间】:2016-01-22 23:38:03
【问题描述】:

我正在尝试下载 PDF,但出现以下错误:HTTP 错误 403:禁止

我知道服务器由于某种原因而阻塞,但我似乎找不到解决方案。

import urllib.request
import urllib.parse
import requests


def download_pdf(url):

full_name = "Test.pdf"
urllib.request.urlretrieve(url, full_name)


try: 
url =         ('http://papers.xtremepapers.com/CIE/Cambridge%20IGCSE/Mathematics%20(0580)/0580_s03_qp_1.pdf')

print('initialized')

hdr = {}
hdr = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2)     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
'Content-Length': '136963',
}



print('HDR recieved')

req = urllib.request.Request(url, headers=hdr)

print('Header sent')

resp = urllib.request.urlopen(req)

print('Request sent')

respData = resp.read()

download_pdf(url)


print('Complete')

except Exception as e:
print(str(e))

【问题讨论】:

标签: python http python-requests urllib


【解决方案1】:

您似乎已经意识到这一点;远程服务器显然正在检查用户代理标头并拒绝来自 Python 的 urllib 的请求。但是urllib.request.urlretrieve() 不允许您更改HTTP 标头,但是,您可以使用urllib.request.URLopener.retrieve()

import urllib.request

opener = urllib.request.URLopener()
opener.addheader('User-Agent', 'whatever')
filename, headers = opener.retrieve(url, 'Test.pdf')

注意您正在使用 Python 3,这些函数现在被视为 "Legacy interface" 的一部分,而 URLopener 已被弃用。因此,您不应在新代码中使用它们。

除此之外,简单地访问一个 URL 会很麻烦。您的代码导入了requests,但您不使用它——您应该使用它,因为它比urllib 容易得多。这对我有用:

import requests

url = 'http://papers.xtremepapers.com/CIE/Cambridge%20IGCSE/Mathematics%20(0580)/0580_s03_qp_1.pdf'
r = requests.get(url)
with open('0580_s03_qp_1.pdf', 'wb') as outfile:
    outfile.write(r.content)

【讨论】:

  • 虽然是个好点 - 它没有解释 403 错误的原因。
  • 这个问题不是在问原因。
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 2011-07-12
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-20
相关资源
最近更新 更多