【问题标题】:How do I remove tags in between other html tags using beautiful soup如何使用漂亮的汤删除其他 html 标签之间的标签
【发布时间】:2015-04-29 18:32:03
【问题描述】:

以此帖子为基础:Can I remove script tags with BeautifulSoup?

假设我有一个这样的 html 文档:

'<td><script class="blah">a</script>baba<script id="blahhhh">b</script></td>'

如何删除脚本标签,但在脚本标签之间保留文本,所以输出将是:

'<td>ababab</td>'

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:
    from BeautifulSoup import BeautifulSoup
    
    VALID_TAGS = ['td']
    
    def sanitize_html(value):
    
        soup = BeautifulSoup(value)
    
        for tag in soup.findAll(True):
            if tag.name not in VALID_TAGS:
                tag.hidden = True
    
        return soup.renderContents()
    

    这会保留无效标签的内容。

    Python HTML sanitizer / scrubber / filter.

    【讨论】:

      【解决方案2】:

      您可以使用简单的getText() 来获取没有子标签的标签内容:

      from bs4 import BeautifulSoup
      
      soup = BeautifulSoup('<td><script class="blah">a</script>baba<script id="blahhhh">b</script></td>')
      td = soup.td
      #update content of <td> to concatenation of all inner text nodes
      td.string = td.getText()
      print(soup)
      

      输出:

      <html><body><td>ababab</td></body></html>
      

      【讨论】:

        猜你喜欢
        • 2012-12-27
        • 2015-05-03
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-13
        相关资源
        最近更新 更多