python BeautifulSoup乱码问题

用爬虫爬取天气数据,需要先获得原网站上城市中文名称与汉语拼音的对应关系。
在编写如下代码进行处理的时候,出现中文乱码。
在这里插入图片描述

查了很多blog发现方法并不好使。除了这位大神。。。。。
这位出现问题就去阅读文档的大神。。。。

https://www.jianshu.com/p/69401b84419e

查阅requests和bs4的官方文档,发现了这样两段描述:

When you make a request, Requests makes educated guesses about the encoding of the response based on the HTTP headers. The text encoding guessed by Requests is used when you access r.text. You can find out what encoding Requests is using, and change it, using the r.encoding property.

Beautiful Soup uses a sub-library called Unicode, Dammit to detect a document’s encoding and convert it to Unicode. The autodetected encoding is available as the .original_encoding attribute of the BeautifulSoup object.Unicode, Dammit guesses correctly most of the time, but sometimes it makes mistakes. Sometimes it guesses correctly, but only after a byte-by-byte search of the document that takes a very long time. If you happen to know a document’s encoding ahead of time, you can avoid mistakes and delays by passing it to the BeautifulSoup constructor as from_encoding.

大意是requests和beautifulsoup都会自行猜测原文的编码方式,然后用猜测出来的编码方式进行解码转换成unicode。大多数时候猜测出来的编码都是正确的,但也有猜错的情况,如果猜错了可以指定原文的编码。
OK,那让我们看一下requests和beautifulsoup是否猜对了原文编码。

response = requests.get('http://www.jjwxc.net/fenzhan/noyq/')
print response.encoding
soup = bs4.BeautifulSoup(response.text, "html.parser")
print soup.original_encoding

运行结果: ISO-8859-1 None

可以发现是由于requests这里对原文的编码猜错了导致乱码的出现,所以我们需要在response.text传给beautifulsoup之前指定编码

response = requests.get('http://www.jjwxc.net/fenzhan/noyq/')

*response.encoding = 'gb18030'

soup = bs4.BeautifulSoup(response.text, "html.parser")
print soup.title

但是运行后发现输出的结果还是乱码。
继续查阅上述语句的相关官方文档,发现beautifulsoup对于输出内容的编码方式有这样一段介绍:
在这里插入图片描述

意即beautifulsoup在输出文本时默认以UTF-8的方式编码,无论原文是否以它进行编码的。如果你不希望以UTF-8的方式编码,可以用prettify()或则==encode()==方式来指定编码。
所以我们将代码更改下:

response = requests.get('http://www.jjwxc.net/fenzhan/noyq/')
response.encoding = 'gb18030'
soup = bs4.BeautifulSoup(response.text, "html.parser")
print soup.title.prettify('gb18030')
print soup.title.encode('gb18030')

可以看到两种指定方式都可以获得无乱码的中文内容。
这里再介绍下prettify()的功能,prettify()除了可以制定输出的编码方式,它的最主要功能是对beautifulsoup的k语法分析树重新排版,使输出的内容整洁易读。

至此,中文乱码的问题解决了。在查找解决方案的过程中,我另外查了下unicode、byte、以及编码和解码方面的知识点。这一块的东西解释起来一时半会儿说不完,而且有些细节的地方我也没完全搞懂,暂时就不卖弄了。对这块内容感兴趣的可以先看下下面这两位大牛的文章,写得非常通俗易懂:

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets
字符编码笔记:ASCII,Unicode和UTF-8

猜你喜欢

转载自blog.csdn.net/b285795298/article/details/85069770
今日推荐