使用 Python requests 库检查二进制内容

Dan*_*Guo 6 python python-requests

查看请求文档,我知道我可以将 response.content 用于二进制内容(例如 .jpg 文件),并将 response.text 用于常规 html 页面。但是,当源是图像并且我尝试访问 r.text 时,脚本会挂起。如何提前确定响应是否包含 html?

我曾考虑检查图像扩展名的 url,但这似乎不是万无一失的。

rlm*_*lms 5

内容类型应该是标题。请参阅文档中的页面。

示例代码:

r = requests.get(url)
if r.headers['content-type'] == 'text/html':
    data = r.text
elif r.headers['content-type'] == 'application/ogg':
    data = r.content
Run Code Online (Sandbox Code Playgroud)