Win*_*ags 4 python content-type python-2.7 mime-types python-requests
我试图确定 URL 的 MIME 类型是否为 PDF 文件,使用requests content-type.
如果查询的 URL 实际上指向托管的 PDF 文件,则以下脚本可以正常工作。但是,使用下面的当前 URL,即使它会导致强制从 Web 下载 PDF 文件(该文件本身在 Chrome 中无法直接从 URL 读取),也会content-type被检测到text/html; charset=utf-8。
import requests
url = 'https://derinet.vontobel.ch/api/kid?isin=DE000VS0URS6&language=en'
def getContentType(url):
r = requests.Session().head(url, allow_redirects=True)
contentType = r.headers['content-type']
print 'Content type: ' + contentType
if (contentType == 'application/pdf') | (contentType == 'application/x-pdf'):
print "content-type is PDF"
else:
print "content-type is not PDF!"
getContentType(url)
Run Code Online (Sandbox Code Playgroud)
有没有办法检查实际生成的 PDF 下载的 MIME 类型,而不是生成它的 html 页面(blob??)?
我已经设置了allow_redirects=True,但在这里似乎无关紧要。
如果您不是发出HEAD请求,而是发出一个GET,您将获得您正在寻找的标头:
$ python
Python 3.7.2 (default, Feb 12 2019, 08:15:36)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> url = 'https://derinet.vontobel.ch/api/kid?isin=DE000VS0URS6&language=en'
>>> r = requests.get(url)
>>> r.headers
{
'Date': 'Wed, 29 May 2019 14:26:56 GMT',
'Server': 'Apache',
'Set-Cookie': 'AL_LB=$xc/70TgziJYWEd9zZwhLxXFDJHocFA0gS9gdbEQS0N0LhFme3uS; Path=/; HTTPOnly; Domain=.vontobel.ch',
'Content-Length': '51764',
'Cache-Control': 'private',
'Content-Disposition': 'attachment; filename=KID_DE000VS0URS6_en.pdf',
'X-Frame-Options': 'SAMEORIGIN',
'Pragma': 'blah',
'Vary': 'User-Agent',
'Keep-Alive': 'timeout=2, max=500',
'Connection': 'Keep-Alive',
'Content-Type': 'application/pdf',
}
Run Code Online (Sandbox Code Playgroud)
标头的差异是由服务器决定的,所以我认为没有办法在没有GET请求的情况下获得正确的标头。
| 归档时间: |
|
| 查看次数: |
4220 次 |
| 最近记录: |