我正在尝试下载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))
答案 0 :(得分:7)
你似乎已经意识到了这一点;远程服务器显然正在检查用户代理标头并拒绝来自Python的urllib的请求。但urllib.request.urlretrieve()
不允许您更改HTTP标头,但是,您可以使用llist
:
import urllib.request
opener = urllib.request.URLopener()
opener.addheader('User-Agent', 'whatever')
filename, headers = opener.retrieve(url, 'Test.pdf')
N.B。您正在使用Python 3,现在这些函数被视为urllib.request.URLopener.retrieve()
的一部分,并且URLopener
已被弃用。因此,您不应在新代码中使用它们。
除此之外,您只需访问一个URL就会遇到很多麻烦。您的代码导入"Legacy interface",但您不使用它 - 您应该这样做,因为它比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)