【问题标题】:Check for binary content with Python requests library使用 Python 请求库检查二进制内容
【发布时间】:2014-04-21 05:45:42
【问题描述】:

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

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

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

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

    示例代码:

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

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 2016-03-16
      • 1970-01-01
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      相关资源
      最近更新 更多