Python BeautifulSoup中文乱码问题的中文乱码问题的2种解决方法种解决方法
解决方法一:解决方法一:
使用python的BeautifulSoup来抓取网页然后输出网页标题,但是输出的总是乱码,找了好久找到解决办法,下面分享给大家
首先是代码
复制代码 代码如下:
from bs4 import BeautifulSoup
import urllib2
url = ‘//www.jb51.net/’
page = urllib2.urlopen(url)
soup = BeautifulSoup(page,from_encoding=”utf8″)
print soup.original_encoding
print (soup.title).encode(‘gb18030’)
file = open(“title.txt”,”w”)
file.write(str(soup.title))
file.close()
for link in soup.find_all(‘a’):
print link[‘href’]
在刚开始测试的时候发现,虽然输出是乱码的,但是写在文件里面却是正常的.然后在网上找了找解决办法才发现
print一个对象的逻辑:内部是调用对象的__str__得到对应的字符串的,此处对应的是soup的__str__ 而针对于soup本身,其
实已经是Unicode编码,所以可以通过指定__str__输出时的编码为GBK,以使得此处正确显示非乱码的中文
而对于cmd:(中文的系统中)编码为GBK,所以只要重新编码为gb18030就可以正常输出了
就是下面这行代码
复制代码 代码如下:
print (soup.title).encode(‘gb18030’)
解决方法二:解决方法二:
BeautifulSoup在解析utf-8编码的网页时,如果不指定fromEncoding或者将fromEncoding指定为utf-8会出现中文乱码的现象。
解决此问题的方法是将Beautifulsoup构造函数中的fromEncoding参数的值指定为:gb18030
复制代码 代码如下:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen(‘//www.jb51.net/’);
soup = BeautifulSoup(page,fromEncoding=”gb18030″)
print soup.originalEncoding
print soup.prettify()
您可能感兴趣的文章您可能感兴趣的文章:Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not strPython爬虫
beautifulsoup4常用的解析方法总结python3解析库BeautifulSoup4的安装配置与基本用法python3第三方爬虫库
BeautifulSoup4安装教程Python爬虫包BeautifulSoup简介与安装(一)Python使用Selenium+BeautifulSoup爬取淘宝搜索页
python基于BeautifulSoup实现抓取网页指定内容的方法Python如何使用BeautifulSoup爬取网页信息