在爬百度"今日热点事件排行榜"的时候发现打印在控制台的中文所有显示乱码,开始怀疑控制台的缘由致使了乱码,后来输出一个中文,发现显示正常。html
#-*- 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)
执行代码控制台返回一串乱码ui
查看网页的源码发现网页的编码方式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)