python删除<div class ="comment> .. any ... </ div>之间的所有内容

Mic*_*Lee 9 html python class

你如何使用python 2.6删除包括的所有内容 <div class="comment"> ....remove all ....</div>

我尝试了各种方式使用re.sub没有任何成功

谢谢

Aym*_*ieh 16

使用像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>
Run Code Online (Sandbox Code Playgroud)

请参阅此问题,了解为什么使用正则表达式解析HTML是一个坏主意.


Ign*_*ams 2

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