【问题标题】:Prevent BeautifulSoup's renderContents() from changing   to Â防止 BeautifulSoup 的 renderContents() 更改为 Â
【发布时间】:2018-06-17 05:32:21
【问题描述】:

我正在使用bs4 对某些文本进行一些处理,但在某些情况下它会将  字符转换为Â。我能说的最好的是这是encoding mismatch from UTF-8 to latin1(或相反?)

我的网络应用程序中的所有内容都是 UTF-8,Python3 是 UTF-8,我已经确认数据库是 UTF-8。

我已将问题缩小到这一行:

print("Before soup: " + text)  # Before soup:  
soup = BeautifulSoup(text, "html.parser")
#.... do stuff to soup, but all commented out for this testing.
soup = BeautifulSoup(soup.renderContents(), "html.parser")  # <---- PROBLEM!
print(soup.renderContents())  # b'\xc3\x82\xc2\xa0'
print("After SOUP: " + str(soup))  # After SOUP: Â

如何防止 renderContents() 更改编码?这个函数上有no documentation

编辑:在进一步研究文档后,this seems to be the key,但我仍然无法解决问题!

print(soup.prettify(formatter="html"))  # &Acirc;&nbsp;

【问题讨论】:

标签: python python-3.x utf-8 beautifulsoup


【解决方案1】:

好的,显然我对文档的阅读不够深入,这里可以找到答案:

来自https://www.crummy.com/software/BeautifulSoup/bs4/doc/#encodings

问题在于提供给 BS 的代码的 sn-p 太短,以至于 BeautifulSoup 的子库 Unicode, Dammit 没有足够的信息来正确猜测编码。

Unicode, Dammit 大部分时间都猜对了,但有时也猜对了 犯错误。 ...你可以避免 通过将错误和延迟传递给 BeautifulSoup 构造函数 from_encoding.

所以关键是每次构造BS的时候都要加上from_encoding="UTF-8"

soup = BeautifulSoup(soup.renderContents(), "html.parser", from_encoding="UTF-8")

【讨论】:

    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 2012-08-12
    • 1970-01-01
    相关资源
    最近更新 更多