【问题标题】:replacing html tags with BeautifulSoup用 BeautifulSoup 替换 html 标签
【发布时间】:2010-10-11 15:51:55
【问题描述】:

我目前正在使用 BeautifulSoup 重新格式化一些 HTML 页面,但遇到了一点问题。

我的问题是原来的 HTML 有这样的东西:

<li><p>stff</p></li>

<li><div><p>Stuff</p></div></li>

还有

<li><div><p><strong>stff</strong></p></div><li>

使用 BeautifulSoup 我希望消除 div 和 p 标签,如果它们存在,但保留 strong 标签。

我正在浏览精美的汤文档,但找不到任何内容。 想法?

谢谢。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    这个问题可能是指较旧版本的 BeautifulSoup,因为使用 bs4 您可以简单地使用 unwrap 函数:

    s = BeautifulSoup('<li><div><p><strong>stff</strong></p></div><li>')
    s.div.unwrap()
    >> <div></div>
    s.p.unwrap()
    >> <p></p>
    s
    >> <html><body><li><strong>stff</strong></li><li></li></body></html>
    

    【讨论】:

      【解决方案2】:

      您可以使用replaceWith 完成您想做的事情。您必须复制要用作替换的元素,然后将其作为参数提供给replaceWithdocumentation for replaceWith 非常清楚如何做到这一点。

      【讨论】:

      【解决方案3】:

      对于这个简单的问题,我看到了很多答案,我也来这里是为了看一些有用的东西,但不幸的是我没有得到我想要的东西,经过几次尝试后,我找到了一个简单的解决方案来解决这个问题,这就是

      p>
      soup = BeautifulSoup(htmlData, "html.parser")
      
      h2_headers = soup.find_all("h2")
      
      for header in h2_headers:
          header.name = "h1" # replaces h2 tag with h1 
      

      所有 h2 标签都转换为 h1。只需更改名称即可转换任何标签。

      【讨论】:

        【解决方案4】:

        您可以编写自己的函数来去除标签:

        import re
        
        def strip_tags(string):
            return re.sub(r'<.*?>', '', string)
        
        strip_tags("<li><div><p><strong>stff</strong></p></div><li>")
        'stff'
        

        【讨论】:

        • 是的,但我实际上想要 那里。同样在浏览了几个随机页面后,只有 div 和 p 需要担心。
        【解决方案5】:

        简单的解决方案让你的整个节点意味着div

        1. 转换为字符串
        2. &lt;tag&gt; 替换为所需的标签/字符串。
        3. 用空字符串替换对应的标签。
        4. 通过传递给 beautifulsoup 将转换后的字符串转换为可解析的字符串

          我为mint做了什么

          例子:

          <div class="col-md-12 option" itemprop="text">
          <span class="label label-info">A</span>
          
          **-2<sup>31</sup> to 2<sup>31</sup>-1**
          

          sup = opt.sup 
              if sup: //opt has sup tag then
          
                   //opts converted to string. 
                   opt = str(opts).replace("<sup>","^").replace("</sup>","") //replacing
          
                   //again converted from string to beautiful string.
                   s = BeautifulSoup(opt, 'lxml')
          
                   //resign to required variable after manipulation
                   opts = s.find("div", class_="col-md-12 option")
          

          输出:

          -2^31 to 2^31-1
          without manipulation it will like this (-231 to 231-1)
          

        【讨论】:

          猜你喜欢
          • 2013-03-10
          • 1970-01-01
          • 2014-03-09
          • 2023-03-28
          • 2021-10-10
          • 1970-01-01
          • 1970-01-01
          • 2017-03-31
          • 2015-06-24
          相关资源
          最近更新 更多