【发布时间】:2010-04-15 23:50:41
【问题描述】:
如何使用 python 2.6 删除包括<div class="comment"> ....remove all ....</div>在内的所有内容
我尝试了各种使用 re.sub 的方法都没有成功
谢谢
【问题讨论】:
如何使用 python 2.6 删除包括<div class="comment"> ....remove all ....</div>在内的所有内容
我尝试了各种使用 re.sub 的方法都没有成功
谢谢
【问题讨论】:
这可以使用像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 的示例,请参阅此问题。
【讨论】:
from lxml import html
doc = html.fromstring(input)
for el in doc.cssselect('div.comment'):
el.drop_tree()
result = html.tostring(doc)
【讨论】:
您无法使用正则表达式正确解析 HTML。使用 HTML 解析器,例如 lxml 或 BeautifulSoup。
【讨论】:
为了记录,使用正则表达式处理 XML 通常是个坏主意。尽管如此:
>>> re.sub('>[^<]*', '>', '<div class="comment> .. any… </div>')
'<div class="comment></div>'
【讨论】:
非正则表达式
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
【讨论】:
使用 Beautiful soup 并执行类似的操作来获取所有这些元素,然后在里面替换
tomatosoup = BeautifulSoup(myhtml)
tomatochunks = tomatosoup.findall("div", {"class":"comment"} )
for chunk in tomatochunks:
#remove the stuff
【讨论】: