I want to remove all html tags except from my string with python i use this:
我想删除所有的html标签,除了我用python的字符串,我用这个:
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
But this remove all my html tags.
但是这删除了我所有的html标签。
1 个解决方案
#1
2
If I understand it right, you want to strip html tags, but to keep some specific ones ? If that's the case - then just keep monitoring the start/end tags, and process them if needed. Example:
如果我理解对了,你想去掉html标签,但保留一些特定的标签?如果是这种情况,那么只需监视开始/结束标记,并在需要时处理它们。例子:
MY_TAGS = ["tag1", "tag2"]
MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def handle_starttag(self, tag, attrs):
if tag in MY_TAGS:
self.fed.append("<%s>" % tag) # tag is only string, no < or >.
def handle_endtag(self, tag):
if tag in MY_TAGS:
self.fed.append("</%s>" % tag)
#1
2
If I understand it right, you want to strip html tags, but to keep some specific ones ? If that's the case - then just keep monitoring the start/end tags, and process them if needed. Example:
如果我理解对了,你想去掉html标签,但保留一些特定的标签?如果是这种情况,那么只需监视开始/结束标记,并在需要时处理它们。例子:
MY_TAGS = ["tag1", "tag2"]
MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def handle_starttag(self, tag, attrs):
if tag in MY_TAGS:
self.fed.append("<%s>" % tag) # tag is only string, no < or >.
def handle_endtag(self, tag):
if tag in MY_TAGS:
self.fed.append("</%s>" % tag)