python替换html中的空标签,python替换html标签,html中的空行,有可能


html中的空行,有可能是空标签组成的例如<p></p>或者<div> </div>或者<p><font> </font></p>,要替换这样的内容,需要使用正则表达式。

请看下面的代码:

__author__ = 'yukaizhao post @ http://byrx.net/'import redef remove_empty_tag(input):    pattern = re.compile(r'<([a-z]+\d?)\b[^>]*>( |[\s ])*</\1>',re.IGNORECASE)    maxLoopTimes = 10    i = 0    while i < maxLoopTimes:        tem = pattern.sub('',input)        if tem == input:            input = tem            break        else:            input = tem        i += 1    return inputif __name__ == '__main__':    output = remove_empty_tag('<div>\n\t   </div>hello')    print output    output = remove_empty_tag('<div><span>    </span></div>hello world')    print output

上述代码执行后,会输出:

hellohello world

空行不见了!!

评论关闭