我正在使用 python 中的请求包请求 url(例如 file = requests.get(url))。 urls 中没有指定扩展名,有时返回一个 html 文件,有时返回一个 pdf。
有没有办法确定返回的文件是 pdf 还是 html,或者更一般地说,文件格式是什么?浏览器能够确定,所以我认为它必须在响应中指明。
最佳答案
这将在 Content-Type
中找到标题,或者 text/html
或 application/pdf
import requests
r = requests.get('http://example.com/file')
content_type = r.headers.get('content-type')
if 'application/pdf' in content_type:
ext = '.pdf'
elif 'text/html' in content_type:
ext = '.html'
else:
ext = ''
print('Unknown type: {}'.format(content_type))
with open('myfile'+ext, 'wb') as f:
f.write(r.raw.read())
关于python-3.x - 确定 url 是 pdf 还是 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38690586/