【问题标题】:Python Regex for html tags用于 html 标签的 Python 正则表达式
【发布时间】:2017-01-03 12:54:04
【问题描述】:

在使用 html 解析器之前,我试图摆脱 HTML 代码的一些元素。我对正则表达式很陌生,这就是为什么我无法理解语法。

我的部分 html 代码如下所示:

<div class="footer" id="footer">
 <other tags> ... bla ... </other tags>
</div>

但似乎页面的相同“部分”可以在某个子页面上以不同方式编写,如下所示:

<div id="footer" class="footer">
 <other tags> ... bla ... </other tags>
</div>

我实现的事情是摆脱特定情况:

footer = re.sub('<div class="footer" id="footer">.*?</div>','',html)

但我想要的是一个更通用的正则表达式,所以如果他应该摆脱每个部分,例如"id="footer" 不管前面是什么

<div ... id="footer" ...> 
<other tags> ... bla ... </other tags>    
</div> 

编辑:在被“讨厌”之前,我对 HTML 解析器也很陌生。

感谢您的帮助!

MG

【问题讨论】:

  • 为什么不能同时使用 HTML 解析器来解决这个问题?
  • .*?改成[\s\S]*?或者使用flags=re.DOTALL,当然如果里面有
    不行的话,改用HTML解析器吧。
  • 我刚刚意识到我可以用soup.findAll('div',{'id':'footer'})找到相应的部分我也可以用HTML解析器摆脱这些部分吗?
  • 为什么要摆脱它?用汤只选择你需要的 div。
  • 标签: python html regex


    【解决方案1】:

    为什么要删除它?正如 Bhavesh 所说,只需选择您想要的。但是,如果您想知道我们是否可以删除它们,那么可以,您可以通过 decompose() 删除它们

    a="""
    <div class="footer" id="footer">
     <p>lskjdf</p>
    </div>
    
    <div id="not_footer" class="footer">
    <p>lskjdf</p>
    </div>
    """
    b = BeautifulSoup(a)
    print b
    print '---------------------'
    print '---------------------'
    for c in b.select('div#footer'):
        c.decompose()
    print b
    

    输出:

    <html><body><div class="footer" id="footer">
    <p>lskjdf</p>
    </div>
    <div class="footer" id="not_footer">
    <p>lskjdf</p>
    </div>
    </body></html>
    ---------------------
    ---------------------
    <html><body>
    <div class="footer" id="not_footer">
    <p>lskjdf</p>
    </div>
    </body></html>
    

    【讨论】:

    • 这对我来说非常有用,基本上正是我想要的。我只想使用除了称为“页脚”的部分之外的所有内容
    猜你喜欢
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2014-08-23
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    相关资源
    最近更新 更多