【问题标题】:python remove everything between <div class="comment> .. any... </div>python 删除 <div class="comment> .. any... </div> 之间的所有内容
【发布时间】:2010-04-15 23:50:41
【问题描述】:

如何使用 python 2.6 删除包括&lt;div class="comment"&gt; ....remove all ....&lt;/div&gt;在内的所有内容

我尝试了各种使用 re.sub 的方法都没有成功

谢谢

【问题讨论】:

标签: python class html


【解决方案1】:

这可以使用像BeautifulSoup这样的HTML解析器轻松可靠地完成:

>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('<body><div>1</div><div class="comment"><strong>2</strong></div></body>')
>>> for div in soup.findAll('div', 'comment'):
...   div.extract()
... 
<div class="comment"><strong>2</strong></div>
>>> soup
<body><div>1</div></body>

有关why parsing HTML using regular expressions is a bad idea 的示例,请参阅此问题。

【讨论】:

    【解决方案2】:

    lxml.html:

    from lxml import html
    doc = html.fromstring(input)
    for el in doc.cssselect('div.comment'):
        el.drop_tree()
    result = html.tostring(doc)
    

    【讨论】:

      【解决方案3】:

      您无法使用正则表达式正确解析 HTML。使用 HTML 解析器,例如 lxmlBeautifulSoup

      【讨论】:

      • 我正在尝试删除所有内容,包括 div 和介于两者之间的所有内容。我似乎在 BeautifulSoup 中找不到任何关于它的参考
      • 另一个例子,比如说我想删除 ...
        ,所以我想删除 html 内容中的所有表格,我不知道你是怎么做的在 BeautifulSoup 中
      • 甚至不在文档“修改解析树”部分的“删除元素”小节中?
      • 是的,我看到了,但你不能删除与该标签相关的特定类或 ID
      【解决方案4】:

      为了记录,使用正则表达式处理 XML 通常是个坏主意。尽管如此:

      >>> re.sub('>[^<]*', '>', '<div class="comment> .. any… </div>')
      '<div class="comment></div>'
      

      【讨论】:

      • 我想知道除了内容之外,OP是否还希望删除DIV标签本身的书挡项目。
      • 是的,基本上,我正在尝试从 div 的开头到结尾删除,例如,您想删除 html 内容中的某些表,例如删除所有 ...
        ,
      【解决方案5】:

      非正则表达式

      pat='<div class="comment">'
      for chunks in htmlstring.split("</div>"):
          m=chunks.find(pat)
          if m!=-1:
             chunks=chunks[:m]
          print chunks
      

      输出

      $ cat file
      one two <tag> ....</tag>
       adsfh asdf <div class="comment"> ....remove
      all ....</div>s sdfds
      <div class="blah" .......
      .....
      blah </div>
      
      $ ./python.py
      one two <tag> ....</tag>
       adsfh asdf
      s sdfds
      <div class="blah" .......
      .....
      blah
      

      【讨论】:

        【解决方案6】:

        使用 Beautiful soup 并执行类似的操作来获取所有这些元素,然后在里面替换

        tomatosoup = BeautifulSoup(myhtml)
        
        tomatochunks = tomatosoup.findall("div", {"class":"comment"} )
        
        for chunk in tomatochunks:
           #remove the stuff
        

        【讨论】:

        猜你喜欢
        • 2011-06-05
        • 1970-01-01
        • 2014-09-23
        • 2017-02-23
        • 1970-01-01
        • 2018-07-31
        • 1970-01-01
        • 2016-05-11
        • 2017-12-31
        相关资源
        最近更新 更多