这里会显示出您选择的修订版和当前版本之间的差别。
— |
modules:beautifulsoup:encode [2010/06/02 01:18] (当前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== BeautifulSoup的编码处理 ====== | ||
+ | BeautifulSoup内部使用的是Unicode,BeautifulSoup会自动检测输入文件的编码类型将其转换为Unicode。 | ||
+ | |||
+ | ===== BeautifulSoup编码检测顺序 ===== | ||
+ | BeautifulSoup按下面的顺序检测编码: | ||
+ | |||
+ | - 创建Soup对象时传递的 fromEncoding 参数; | ||
+ | - XML/HTML文件自己定义的编码; | ||
+ | - 文件开始几个字节所表示的编码特征,此时能判断的编码只可能是以下编码之一:UTF-*,EBCDIC,和ASCII。 | ||
+ | - 如果你安装了[[modules:chardet|chardet]],BeautifulSoup会用chardet检测文件编码。 | ||
+ | - UTF-8 | ||
+ | - Windows-1252 | ||
+ | |||
+ | 在BeautifulSoup的源文件中有这么一句代码: | ||
+ | <code python> | ||
+ | DEFAULT_OUTPUT_ENCODING = "utf-8" | ||
+ | </code> | ||
+ | 说明BeautifulSoup默认输出编码是utf-8编码,大家在使用的时候需要注意这个。 | ||
+ | |||
+ | |||
+ | ===== BeautifulSoup中编码处理函数 ===== | ||
+ | BeautifulSoup中的originalEncoding变量可以给出BeautifulSoup检测出的文件编码。 | ||
+ | |||
+ | <code python> | ||
+ | import urllib2 | ||
+ | from BeautifulSoup import BeautifulSoup | ||
+ | |||
+ | doc = urllib2.urlopen("http://www.pythonclub.org/") | ||
+ | soup = BeautifulSoup(doc) | ||
+ | soup.originalEncoding | ||
+ | #u'utf-8' | ||
+ | </code> | ||
+ | |||
+ | ===== BeautifulSoup处理中文编码 ===== | ||
+ | |||
+ | |||
+ |