如果您想要的只是 <s> 部分,为什么不直接过滤掉而不是删除呢?
例如:
from bs4 import BeautifulSoup
sample = """
<span><s>Something</s>Anything</span>
"""
soup = BeautifulSoup(sample, "lxml")
print(soup.find("s"))
这会让你:
<s>Something</s>
如果您有更多带有<s> 的<span> 标签,您可以这样做:
sample = """
<span><s>Something</s>Anything</span>
<span><s>More of Something</s>Less of Anything</span>
"""
print([t.find("s") for t in soup.find_all("span")])
要得到这个:
[<s>Something</s>, <s>More of Something</s>]
但是,如果你想删除标签,那么你最终会得到一个空的HTML(至少在这个简单的情况下)。
看这个:
from bs4 import BeautifulSoup
sample = """
<span><s>Something</s>Anything</span>
"""
soup = BeautifulSoup(sample, "lxml")
for tag in soup.find_all(True):
if tag.name == "span":
tag.extract()
print(soup)
产生这个:
<html><head></head><body>
</body></html>
或者,更短的,带有列表理解:
print([t.extract() for t in soup.find_all("span")])
给:[]
所以,我想,最好的办法是过滤掉不需要的标签。