请求后损坏的PDF文件。使用Python获取()

2024-03-29 05:55:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

Tags: 文件importhttpurlstreamgetpdf情况
1条回答
网友
1楼 · 发布于 2024-03-29 05:55:27

修复标题信息可使其正常工作

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)

相关问题 更多 >