使用 Python 的 requests.get() 后损坏的 PDF 文件



我正在尝试使用requests.get((下载PDF文件。它适用于我找到的大多数测试 PDF 文件,但在这种情况下它不适用于,并且文件已损坏。如果我使用浏览器打开 URL 并保存文件,它工作正常。我尝试使用"流"分块下载它,但结果相同。你能向我解释一下我错过了什么吗?

import requests
file_url = 'http://medianet.edmond-de-rothschild.fr/edram/pdf/kiid_fr0010172767_en_20200120_20200128_1954.pdf'

headers = {'Content-type': 'application/pdf'}
r = requests.get(file_url, headers=headers)
with open("python.pdf", "wb") as pdf:
pdf.write(r.content)
pdf.close()

修复标头信息使其正常工作。

import requests
file_url = "http://medianet.edmond-de-rothschild.fr/edram/pdf/kiid_fr0010172767_en_20200120_20200128_1954.pdf"
headers = {
"User-Agent": "PostmanRuntime/7.20.1",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "8eb5df70-4da6-4ba1-a9dd-e68880316cd9,30ac79fa-969b-4a24-8035-26ad1a2650e1",
"Host": "medianet.edmond-de-rothschild.fr",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"cache-control": "no-cache",
}
r = requests.get(file_url, file_url, headers=headers)
with open("python.pdf", "wb") as pdf:
pdf.write(r.content)

最新更新