BeautifulSoup解码错误

bha*_*esh 5 python beautifulsoup

我正在尝试使用Beautiful Soup解析由Evernote生成的html文件.代码是:

html = open('D:/page.html', 'r')
soup = BeautifulSoup(html)
Run Code Online (Sandbox Code Playgroud)

它给出以下错误:

File "C:\Python33\lib\site-packages\bs4\__init__.py", line 161, in __init__ markup = markup.read() File "C:\Python33\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 24274: character maps to <undefined>

如何解决这个问题?

Mar*_*ers 14

通过编码字节串,或甚至一个文件对象(在二进制模式打开),以代替BeautifulSoup; 它会处理解码:

with open('D:/page.html', 'rb') as html:
    soup = BeautifulSoup(html)
Run Code Online (Sandbox Code Playgroud)

BeautifulSoup在文档本身中查找HTML元数据(例如<meta>具有charset解码文档的属性标记 ;未能使用该chardet库来对使用的编码进行(教育性的)猜测.chardet使用有关用于提供的字节序列的启发式和统计信息BeautifulSoup与最可能的编解码器.

如果您有更多上下文并且已经知道要使用的正确编解码器,请使用from_encoding参数传递:

with open('D:/page.html', 'rb') as html:
    soup = BeautifulSoup(html, from_encoding=some_explicit_codec)
Run Code Online (Sandbox Code Playgroud)

请参阅文档Encodings部分.