zoukankan      html  css  js  c++  java
  • Request库使用response.text返回乱码问题

    我们日常使用Request库获取response.text,这种调用方式返回的text通常会有乱码显示:

    import requests
    
    res = requests.get("https://www.baidu.com")
    print(res.text)

    #...name=tj_briicon class="bri" style="display: block;">更多产品</a> </div> </di...

    如上:出现了乱码

    解决方案:一

    import requests
    
    res = requests.get("https://www.baidu.com")
    print(res.content.decode('utf-8'))

    #...name=tj_briicon class="bri" style="display: block;">更多产品</a> </div> ...

      

    如上:使用这种方法调用显示了正确的中文

      使用res.content时,返回的数据格式其实是二进制格式,然后通过decode()转换为utf-8,这样就解决了通过response.text直接返回显示乱码的问题

    解决方案:二

    import requests
    
    res = requests.get("https://www.baidu.com")
    res.encoding = 'utf-8'
    print(res.text)
    #...name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </d...

    Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 response.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 response.encoding 属性来改变它

  • 相关阅读:
    记录我的第一次电话面试
    Spring整合Mybatis出现Access denied for user 'Think'@'localhost' (using password: YES)
    Lombok基本使用
    log4j整理
    mybatis常用的配置解析
    Java实现邮件发送
    Java获取UUID
    Java实现文件下载
    Java实现文件上传
    Java跳出多层for循环的4种方式
  • 原文地址:https://www.cnblogs.com/nieliangcai/p/10334947.html
Copyright © 2011-2022 走看看