【转】Python BeautifulSoup 中文乱码解决方法

这篇文章主要介绍了Python BeautifulSoup中文乱码问题的2种解决方法,须要的朋友能够参考下python

解决方法一: 使用python的BeautifulSoup来抓取网页而后输出网页标题,可是输出的老是乱码,找了很久找到解决办法,下面分享给你们 首先是代码 复制代码 代码以下:函数

在刚开始测试的时候发现,虽然输出是乱码的,可是写在文件里面倒是正常的.而后在网上找了找解决办法才发现 print一个对象的逻辑:内部是调用对象的__str__获得对应的字符串的,此处对应的是soup的__str__ 而针对于soup自己,其实已是Unicode编码,因此能够经过指定__str__输出时的编码为GBK,以使得此处正确显示非乱码的中文 而对于cmd:(中文的系统中)编码为GBK,因此只要从新编码为gb18030就能够正常输出了 就是下面这行代码 复制代码 代码以下: print (soup.title).encode('gb18030')测试

from bs4 import BeautifulSoup
import urllib2

url = 'http://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']

解决方法二: BeautifulSoup在解析utf-8编码的网页时,若是不指定fromEncoding或者将fromEncoding指定为utf-8会出现中文乱码的现象。 解决此问题的方法是将Beautifulsoup构造函数中的fromEncoding参数的值指定为:gb18030 复制代码 代码以下:编码

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://www.jb51.net/');
soup = BeautifulSoup(page,fromEncoding="gb18030")
print soup.originalEncoding
print soup.prettify()
相关文章
相关标签/搜索