您的位置:首页 > 编程语言 > Python开发

解决python中遇到的乱码问题

2017-12-10 19:23 288 查看

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

1 # -*- coding:utf-8 -*-
2 from __future__ import unicode_literals
3
4 import chardet
5
6
7 def smart_decoder(raw_content, default_encoding_list=("utf-8", "gb18030")):
8     """
9     将字符串解码成unicode
10     :type default_encoding_list: list of str
11     :rtype: unicode
12     :type raw_content: str|unicode
13     """
14     if isinstance(raw_content, unicode):
15         return raw_content
16
17     encoding = chardet.detect(raw_content).get("encoding", "utf-8")
18
19     try:
20         return raw_content.decode(encoding)
21     except UnicodeEncodeError as e:
22         for encoding in default_encoding_list:
23             try:
24                 return raw_content.decode(encoding)
25             except UnicodeEncodeError as e:
26                 pass
27         raise e
28
29
30 if __name__ == '__main__':
31     import requests
32
33     a = requests.get("https://www.baidu.com").content
34     smart_decoder(a)

 

2. requests响应结果乱码

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

原因:

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

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

 

解决思路:

  人工解码,处理编码错误

 

程序demo

1 def parse_response(response):
2     """
3     手工对requests的响应内容解码
4     :rtype: unicode
5     """
6     return smart_decoder(response.content)

 

源码见blog.

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: