python网络通信时出现乱码_解决python中遇到的乱码问题

1. 解决中文乱码的一种可行方法

1 #-*- coding:utf-8 -*-

2 from __future__ importunicode_literals3

4 importchardet5

6

7 def smart_decoder(raw_content, default_encoding_list=("utf-8", "gb18030")):8 """

9 将字符串解码成unicode10 :type default_encoding_list: list of str11 :rtype: unicode12 :type raw_content: str|unicode13 """

14 ifisinstance(raw_content, unicode):15 returnraw_content16

17 encoding = chardet.detect(raw_content).get("encoding", "utf-8")18

19 try:20 returnraw_content.decode(encoding)21 exceptUnicodeEncodeError as e:22 for encoding indefault_encoding_list:23 try:24 returnraw_content.decode(encoding)25 exceptUnicodeEncodeError as e:26 pass

27 raisee28

29

30 if __name__ == '__main__':31 importrequests32

33 a = requests.get("https://www.baidu.com").content34 smart_decoder(a)

2. requests响应结果乱码

使用requests请求网址,获取响应response, 通过response.text得到的网页内容,有时候会出现乱码的情况。

原因:

分析源代码发现,调用respose.text 其实就是对 response.content执行解码操作。编码通过chardet判断。

乱码的关键是,chardet获取的编码可能不正确,但在执行response.content.decode时,程序会直接忽略编码异常,从而导致使用错误的编码解码。

解决思路:

人工解码,处理编码错误

程序demo

1 defparse_response(response):2 """

3 手工对requests的响应内容解码4 :rtype: unicode5 """

6 return smart_decoder(response.content)

源码见blog.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值