代码之家  ›  专栏  ›  技术社区  ›  43Tesseracts

防止BeautifulSoup的renderContents()更改为

  •  2
  • 43Tesseracts  · 技术社区  · 7 年前

    我在用 bs4 在某些文本上做一些工作,但在某些情况下它会转换   字符到 Â .我只能说这是 encoding mismatch from UTF-8 to latin1 (还是相反?)

    我的web应用程序中的所有内容都是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;
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   43Tesseracts    7 年前

    好吧,显然我对医生的理解不够深入,答案就在这里:

    https://www.crummy.com/software/BeautifulSoup/bs4/doc/#encodings 以下内容:

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

    Unicode,该死的 大多数时候猜测正确,但有时 犯错误。…你可以避免 将错误和延迟传递给美丽的汤构造者 from_encoding .

    所以关键是要增加 from_encoding="UTF-8" 每次建造BS时:

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