Python beautifulsoup 中文乱码

在爬百度"今日热点事件排行榜"的时候发现打印在控制台的中文全部显示乱码,开始怀疑控制台的原因导致了乱码,后来输出一个中文,发现显示正常。

#-*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
res = requests.get("http://top.baidu.com/buzz?b=341&fr=topbuzz_b1&qq-pf-to=pcqq.discussion")
soup = BeautifulSoup(res.text,'lxml')
print(soup.head.title.text)

执行代码控制台返回一串乱码

查看网页的源码发现网页的编码方式gbk,BeautifulSoup解析后得到的soup,打印出来是乱码,实际上其本身已经是正确的(从原始的GB2312编码)解析(为Unicode)后的了。之所以乱码,那是因为,打印soup时,调用的是__str__,其默认是UTF-8,所以输出到GBK的cmd中,才显示是乱码(参考一些文章

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
#-*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
res = requests.get("http://top.baidu.com/buzz?b=341&fr=topbuzz_b1&qq-pf-to=pcqq.discussion")
res.encoding = 'gb18030' 
soup = BeautifulSoup(res.text,'lxml')
print(soup.head.title.text)

  

原文地址:https://www.cnblogs.com/mengyu/p/6759671.html