使用 python-requests 和 python-magic,我想测试 web 资源的 mime 类型而不获取其所有内容(特别是如果该资源恰好是 ogg 文件或 PDF 文件)。根据结果,我可能会决定全部获取。但是,在测试 mime 类型后调用 text 方法只会返回尚未使用的内容。如何在不使用响应内容的情况下测试 mime 类型?
下面是我当前的代码。
import requests
import magic
r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
mime = magic.from_buffer(r.iter_content(256).next(), mime=True)
if mime == "text/html":
print(r.text) # I'd like r.text to give me the entire response content
谢谢!
最佳答案
如果 'content-type' 足够,您可以发出 HTTP 'Head' 请求而不是 'Get',只接收 HTTP header 。
import requests
url = 'http://www.december.com/html/demo/hello.html'
response = requests.head(url)
print response.headers['content-type']
关于python-requests:获取响应内容的头部而不全部消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197854/