【问题标题】:BeautifulSoup: how to keep HTML entity, &qout;BeautifulSoup:如何保持 HTML 实体,"
【发布时间】:2021-03-18 09:45:23
【问题描述】:

来自https://www.crummy.com/software/BeautifulSoup/bs4/doc/#output-formatters,它说

如果你给 Beautiful Soup 一个包含 HTML 实体的文档,比如 “&lquot;”,它们将被转换为 Unicode 字符:

soup = BeautifulSoup("&ldquo ; Wow!&rdquo ; 他说。", 'html.parser')

str(汤)

'“哇!”他说。'

有什么方法可以修改这种行为并使其保留'&dlquo;''”''"'等实体 strong> 用 BeautifulSoup 处理 html 或 xml 的字符串?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您是否尝试阅读该文档部分的其余部分?您可以通过将formatter="html" 传递给soup.encode 来取回实体:

    >>> soup.encode(formatter="html")
    b'“ ; Wow!” ; he said.'
    

    另一种方法是在传递给 BeautifulSoup 之前将 & 替换为 &

    >>> html = "&ldquo ; Wow!&rdquo ; he said."
    >>> soup = BeautifulSoup(html.replace("&", "&"), 'html.parser')
    >>> print(soup.get_text())
    &ldquo ; Wow!&rdquo ; he said.
    

    【讨论】:

    • 我试过了,但它对'&qout;'不起作用
    • 您的第二种方法不是意味着文档的内存表示格式不正确...在您更换后意味着不同的东西吗?其他选项只是处理外部表示,但不改变实际对象,对吧?
    • & for &很有趣。 text 属性或 get_text() 返回实体转换的字符串,结果保留原始格式。它可以工作,但可能会导致代码不那么可读。
    猜你喜欢
    • 2012-03-25
    • 2019-09-03
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    相关资源
    最近更新 更多