• python requests的content和text方法的区别


    转自“https://blog.csdn.net/xie_0723/article/details/51361006

    一直在想requests的content和text属性的区别,从print 结果来看是没有任何区别的

    看下源码:

        @property
        def text(self):
            """Content of the response, in unicode.
    
            If Response.encoding is None, encoding will be guessed using
            ``chardet``.
    
            The encoding of the response content is determined based solely on HTTP
            headers, following RFC 2616 to the letter. If you can take advantage of
            non-HTTP knowledge to make a better guess at the encoding, you should
            set ``r.encoding`` appropriately before accessing this property.
            """
    
        #content的完整代码就不贴了。
        @property
        def content(self):
            """Content of the response, in bytes."""
    
    • 结论是:

    resp.text返回的是Unicode型的数据。

    resp.content返回的是bytes型也就是二进制的数据。


    也就是说,如果你想取文本,可以通过r.text。

    如果想取图片,文件,则可以通过r.content。

    (resp.json()返回的是json格式数据)

    • 举个栗子
    # 例如下载并保存一张图片
    
    import requests
    
    jpg_url = 'http://img2.niutuku.com/1312/0804/0804-niutuku.com-27840.jpg'
    
    content = requests.get(jpg_url).content
    
    with open('demo.jpg', 'wb') as fp:
        fp.write(content)
    ---------------------------------------------------------------------------------------以下是正确的

    1、重点理解

    response.text返回的类型是str

    response.content返回的类型是bytes,可以通过decode()方法将bytes类型转为str类型

    推荐使用:response.content.decode()的方式获取相应的html页面

    2、扩展理解

    • response.text
      解码类型:根据HTTP头部对响应的编码做出有根据的推测,推测的文本编码
      如何修改编码方式:response.encoding = 'gbk'
    • response.content
      解码类型:没有指定
      如何修改编码方式:response.content.decode('utf8')
     
  • 相关阅读:
    Python 爬邮箱
    Attempting to fetch value instead of handling error Internal: failed to get device attribute 13 for device 0: CUDA_ERROR_UNKNOWN: unknown error
    Ubuntu使用TinyOS常见错误
    Ubuntu16.04中安装TinyOS
    cmake 常用命令
    微信开发小结-PHP
    KVC&KVO&NSNotification
    IOS 图片拉伸技巧
    IOS学习-报错误 Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
    小程序订阅消息(模板消息已被废弃)
  • 原文地址:https://www.cnblogs.com/fengff/p/9007586.html
Copyright © 2020-2023  润新知