0
这是从许多“删除标签但保留内容”的问题的反面 - 如何删除标签内的文本(例如<span foo="bar">text I don't want</span>
,但保留标签(即<span foo="bar"></span>
)?删除标签文本(但保留标签)在BeautifulSoup4
这是从许多“删除标签但保留内容”的问题的反面 - 如何删除标签内的文本(例如<span foo="bar">text I don't want</span>
,但保留标签(即<span foo="bar"></span>
)?删除标签文本(但保留标签)在BeautifulSoup4
只需设置tag.string
为空字符串,或者使用tag.string.replace_with()
。
bs = BeautifulSoup(html)
for tag in bs.find_all('span'):
# Strip all text by setting it to an empty string
tag.string = ""
# Or strip all text by replacing the string
tag.string.replace_with("")