简体   繁体   English

在BeautifulSoup4中删除标签文本(但保留标签)

[英]Remove tag text (but keep tag) in BeautifulSoup4

这与许多“删除标签但保留内容”问题相反:如何删除标签内的文本(例如, <span foo="bar">text I don't want</span>但保留标签(即<span foo="bar"></span> )?

Just set tag.string to an empty string. 只需将tag.string设置为空字符串即可。 Alternatively, use tag.string.replace_with() . 或者,使用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("")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM