为什么我的PDF的标题['contenttype']是“text/html;charset=utf8”?

2024-04-20 13:20:23 发布

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

当我需要“application/pdf”时,从它的url下载pdf文件时,我看到的是headers['content-type']'text/html; charset=utf-8'。为什么我在设置Headers内容类型的时候也这么做?在

代码示例:

import requests
from requests.auth import HTTPBasicAuth
from pprint import pprint

file = 'url.pdf'
username = 'myusername'
password = 'mypassword'
headers = {'content-type': 'application/pdf', 'User-Agent': 'myUser-Agent'}
pdf_fname = 'new.pdf'

resp = requests.get(
    file, headers=headers, 
    auth=HTTPBasicAuth(username, password),
    proxies=proxyDict
)

with open(pdf_fname,'wb') as f:
    f.write(resp.content)

pprint(resp.headers['content-type'])

Tags: fromimportauthurlpdfapplicationtypeusername
1条回答
网友
1楼 · 发布于 2024-04-20 13:20:23

GET请求没有内容体,因此不需要Content-Type头。在那里设置标题毫无意义。HTTP服务器通常会忽略它们接收到的任何GET请求的标头。在

您观察到的头是由您联系的HTTP服务器设置的,如果您从服务器接收到的数据是PDF文件,那么响应带有不正确的Content-Type报头,那么这完全在服务器上,而不是在您的代码或requests上。只需忽略标题,或与您正在联系的站点的管理员联系,要求他们更正错误。在

但是,如果服务器实际上正在向您发送HTML,那么您可能需要将该HTML保存在某个位置,然后在浏览器中打开它,以查看服务器试图告诉您的内容。它可能是特定的错误消息或登录页面。我们不能告诉你是否是这样,我们只是不知道这个网站是如何运作的。在

另请参阅another answer of mine,其中介绍了requestsHTTP请求的故障排除,这与web浏览器处理相同url的方式不同。在

相关问题 更多 >