【问题标题】:Corrupted PDF file after requests.get() with Python使用 Python 的 requests.get() 后损坏的 PDF 文件
【发布时间】:2020-02-05 10:57:11
【问题描述】:

我正在尝试使用 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()

【问题讨论】:

  • 您可能会错过根本没有下载 PDF。检查您下载的内容——它是 HTML。
  • 你知道为什么它返回 HTML,尽管 url 明确以 PDF 结尾吗?我应该如何以最简单的方式获取其中的 pdf 部分?

标签: python python-3.x pdf python-requests


【解决方案1】:

修复标题信息使其工作。

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)

【讨论】:

  • 谢谢。它确实有效,但我不确定标题中的哪些数据使其有效以及为什么。如果你知道请分享,以便我以后可以自己调试类似的情况。
  • 我使用postman先发送get请求。 Postman 在下面做了一些 http 魔术来生成适当的标头。我刚刚收集了那个信息。 :D
猜你喜欢
  • 2015-10-12
  • 1970-01-01
  • 2022-01-06
  • 2011-01-12
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
  • 2014-03-24
相关资源
最近更新 更多