使用Python请求下载PDF时访问被拒绝

时间:2019-07-11 11:03:26

标签: python http python-requests

我正在寻找使用python下载PDF并使用requests库。以下代码可用于某些PDF文档,但对于少数文档则会引发错误。

from pathlib import Path
import requests

filename = Path('c:/temp.pdf')
url = 'https://www.rolls-royce.com/~/media/Files/R/Rolls-Royce/documents/investors/annual-reports/rr-full%20annual%20report--tcm92-55530.pdf'
response = requests.get(url,verify=False)
filename.write_bytes(response.content)

以下是确切的答复(response.content),但是,我可以使用chrome浏览器下载相同的文档,而不会出现任何错误

b'<HTML><HEAD>\n<TITLE>Access Denied</TITLE>\n</HEAD><BODY>\n<H1>Access Denied</H1>\n \nYou don\'t have permission to access "http&#58;&#47;&#47;www&#46;rolls&#45;royce&#46;com&#47;&#37;7e&#47;media&#47;Files&#47;R&#47;Rolls&#45;Royce&#47;documents&#47;investors&#47;annual&#45;reports&#47;rr&#45;full&#37;20annual&#37;20report&#45;&#45;tcm92&#45;55530&#46;pdf" on this server.<P>\nReference&#32;&#35;18&#46;36ad4d68&#46;1562842755&#46;6294c42\n</BODY>\n</HTML>\n'

有什么办法摆脱这种情况?

1 个答案:

答案 0 :(得分:0)

您之所以得到403 Forbidden,是因为默认情况下,requests发送User-Agent: python-requests/2.19.1标头,而服务器拒绝了您的请求。

您可以从浏览器中获取此标头的正确值,一切都会很好。

例如:

import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 YaBrowser/19.6.1.153 Yowser/2.5 Safari/537.36'}
url = 'https://www.rolls-royce.com/~/media/Files/R/Rolls-Royce/documents/investors/annual-reports/rr-full%20annual%20report--tcm92-55530.pdf'

r = requests.get(url, headers=headers)
print(r.status_code)  # 200