簡體   English   中英

在BeautifulSoup4中刪除標簽文本(但保留標簽)

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

這與許多“刪除標簽但保留內容”問題相反:如何刪除標簽內的文本(例如, <span foo="bar">text I don't want</span>但保留標簽(即<span foo="bar"></span> )?

只需將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("")

暫無
暫無

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

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