BeautifulSoup 奇怪地美化非英语(西里尔)字符编码

BeautifulSoup prettify encoding non-English (Cyrillic) characters strangely

我有 HTML 西里尔字符。我正在使用 BeautifulSoup4 来处理这个。它工作得很好,但是当我去美化时,它会将所有西里尔字符转换为其他字符。这是一个使用 Python3:

的虚拟示例
from bs4 import BeautifulSoup

hello = '<span>Привет, мир</span>'
soup = BeautifulSoup(hello, 'html.parser')
print("Before prettify:\n{}".format(soup))
soup = soup.prettify(formatter='html')
print("\nafter prettify:\n{}".format(soup))

这是它生成的输出:

Before prettify:
<span>Привет, мир</span>

after prettify:
<span>
 &Pcy;&rcy;&icy;&vcy;&iecy;&tcy;, &mcy;&icy;&rcy;
</span>

它正确地格式化了 HTML(将标签放在它们的行上),但它正在将西里尔字符转换为其他字符(老实说,我什至不确定那是什么编码。)

我已经尝试过各种方法来防止这种情况; prettify(encoding=None, formatter='html')prettify(encoding='utf-8', formatter='html'),我也尝试过改变我创建 soup 对象的方式:soup = BeautifulSoup(hello.encode('utf-8'), 'html.parser')soup = BeautifulSoup(hello, 'html.parser', from_encoding='utf-8') - 在美化期间似乎没有改变西里尔字符发生的事情。

我想这一定是我在某处使用编码参数犯的一个非常简单的错误,但在搜索互联网和 BS4 文档后,我无法弄清楚这一点。 有没有办法使用 BeautifulSoup 的美化,但保持原来的西里尔字符,或者这是不可能的?

编辑:我现在意识到(感谢 DYZ 的回答),从美化调用中删除 formatter='html' 将停止 BeautifulSoup 转换西里尔字符。不幸的是,这也会删除文档中的任何 &nbsp 个字符。在查看 BS4's output-formatters documentation, it seems the solution is to create a custom formatter using BS's Formatter class, and specifying this in the call to prettify - soup.prettify(formatter=my_formatter). I'm not sure yet what that would entail, though. I have posted this Whosebug question 之后尝试解决这个单独的问题。 (格式美化以同时保留   和 Cryillic 字符 编辑:查看该问题的答案 - 我终于弄明白了。)

来自documentation

If you pass in formatter="html", Beautiful Soup will convert Unicode characters to HTML entities whenever possible.

如果不需要,请不要使用 HTML 格式化程序:

soup.prettify()
#'<span>\n Привет, мир\n</span>'