最近在自学用python进行网页数据抓取,结果被中文乱码的问题折腾了好久。网上google了各种解决方案都无法解决我遇到的问题,索性自己深入的研究了下,终于把这难题给解决了。在此梳理下整个分析过程。
一开始我的代码是这样写的:
response = requests.get('http://www.jjwxc.net/fenzhan/noyq/')
soup = bs4.BeautifulSoup(response.text, "html.parser")
print soup.title
查看jjwxc.net的源码,可以得知该网站的中文编码是gb18030
<meta http-equiv="Content-Type" content="text/html; charset=gb18030" />
于是进一步查阅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
response = requests.get('http://www.jjwxc.net/fenzhan/noyq/')
response.encoding = 'gb18030'
soup = bs4.BeautifulSoup(response.text, "html.parser")
print soup.title
意即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')
运行结果:
<title>
非言情小说网|同人小说|古代纯爱小说|现代纯爱小说|同人纯爱小说|动漫同人小说【晋江文学城】bl小说站
</title>
<title>非言情小说网|同人小说|古代纯爱小说|现代纯爱小说|同人纯爱小说|动漫同人小说【晋江文学城】bl小说站</title>
至此,中文乱码的问题解决了。在查找解决方案的过程中,我另外查了下unicode、byte、以及编码和解码方面的知识点。这一块的东西解释起来一时半会儿说不完,而且有些细节的地方我也没完全搞懂,暂时就不卖弄了。对这块内容感兴趣的可以先看下下面这两位大牛的文章,写得非常通俗易懂:
2024 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123