Beautiful Soup处理unicode
在python众多的辅助脚本中,beautiful soup(美丽的汤)无疑是耀眼的一个。
BS解析HTML,XML相当方便,但其中还是有一些问题的,尤其是在处理unicode的问题上,其实这也不能怪BS,毕竟python的unicode解决方案就不是那么的优雅,当然pyython 3.0就好多了。
由于BS在解析HTML时,要把所有内容全部转换成unicode来进行存储,这就出现了一个问题,BS怎么判断原始的HTML文件的编码方式?
BS根据以下规则来判断:
* 可以通过fromEncoding参数传递编码类型给soup的构造器
* 通过文档本身找到编码类型:例如XML的声明或者HTML文档http-equiv的META标签。如果Beautiful Soup在文档中发现编码类型,它试着使用找到的类型转换文档。但是,如果你明显的指定一个编码类型,并且成功使用了编码:这时它会忽略任何它在文档中发现的编码类型。
* 通过嗅探文件开头的一下数据,判断编码。如果编码类型可以被检测到,它将是这些中的一个:UTF-*编码,EBCDIC或者ASCII。
* 通过chardet 库,嗅探编码,如果你安装了这个库。
* UTF-8
* Windows-1252
* An encoding you pass in as the fromEncoding argument to the soup constructor.
* An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.
* An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.
* An encoding sniffed by the chardet library, if you have it installed.
* UTF-8
* Windows-1252
这并不能保证结果的正确性,所以,在BS不能正确判断的时候,需要使用者指定当前HTML页面的编码方式。
例如:
soup = BeautifulSoup(gbk, fromEncoding="gbk")
这样就ok了

