【问题标题】:How to get text of this html element while preserving some inner tags如何在保留一些内部标签的同时获取此 html 元素的文本
【发布时间】:2021-10-27 21:24:57
【问题描述】:

我正在使用 BeautifulSoup,并在我的文档中找到了一个元素,如下所示:

<p><a id="_Toc374204393"></a><a id="_Toc374204469"></a>Hershey's<sup>®</sup> makes yummy chocolate</p>

我想提取

Hershey's<sup>®</sup> makes yummy chocolate

我知道我可以拿走这个项目并抓住它的.contents,然后如果它不包含&lt;a&gt;,则重新加入文本,但这似乎是一种超级笨拙的方法。我还能如何得到这个文本?使用 get_text() 之类的方法将文本返回给我,但没有我想保留的 &lt;sup&gt; 标记。

【问题讨论】:

  • 您是如何继续使用.contents 方法的?我提供的答案比这更好吗?
  • .contents 会给我类似[a id="_Toc374204393"&gt;&lt;/a&gt;,&lt;a id="_Toc374204469"&gt;&lt;/a&gt;,"Hershey's",&lt;sup&gt;®&lt;/sup&gt;, "makes yummy chocolate"] 的东西,我可以从中迭代并以某种方式删除 a 标签。我想这是一个很好的答案,但似乎有一种方法可以做我想做的事。也许没有。

标签: python html beautifulsoup


【解决方案1】:

你可以使用next_siblings:

from bs4 import BeautifulSoup

html = """<p><a id="_Toc374204393"></a><a id="_Toc374204469"></a>Hershey's<sup>®</sup> makes yummy chocolate</p>"""
soup = BeautifulSoup(html, "html.parser")

print(
    "".join(str(x) for x in soup.find("a", id="_Toc374204469").next_siblings)
)

输出:

Hershey's<sup>®</sup> makes yummy chocolate

【讨论】:

  • 这适用于这种特殊情况,但并不理想,因为我有其他字符串没有这个 id 属性可以打开,所以它一般不起作用。
  • @gammapoint "".join(str(x) for x in soup.select_one("a:last-of-type").next_siblings) 工作吗?
  • 谢谢,孟德尔。这也可能有效,但我不确定它是否比我刚刚在上面找到并发布的bleach 的方法更好。
【解决方案2】:

迄今为止我发现的最佳解决方案是使用bleach 包。有了这个,我就可以了

import bleach
bleach.clean(my_html, tags=['sup'], strip=True)

起初这对我不起作用,因为我的 html 是 BeautifulSoup Tag 对象,而漂白想要 html。所以我只是做了str(Tag) 来获取 html 表示并将其提供给漂白。

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多