簡體   English   中英

如何在保留一些內部標簽的同時獲取此 html 元素的文本

[英]How to get text of this html element while preserving some inner tags

我正在使用 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 ,然后如果它不包含<a> ,則重新加入文本,但這似乎是一種超級hacky的方法。 我還能如何獲得此文本? 使用get_text()類的方法返回文本但沒有我想保留的<sup>標簽。

您可以使用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

迄今為止我發現的最佳解決方案是使用bleach包。 有了這個,我就可以了

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

起初這對我不起作用,因為我的 html 是一個 BeautifulSoup Tag對象,而漂白劑需要 html。 所以我只是做了str(Tag)來獲取 html 表示並將其喂給漂白劑。

這是迄今為止所需的解決方案

from bs4 import BeautifulSoup

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

soup = BeautifulSoup(html_doc, 'html.parser')

s = soup.find('p')
for t in s.select('p a'):
    t.decompose()

print(s)

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM