Home >Backend Development >PHP Tutorial >Python 清理HTML标签类似PHP的strip_tags函数功能(二)

Python 清理HTML标签类似PHP的strip_tags函数功能(二)

WBOY
WBOYOriginal
2016-06-23 13:48:181062browse

没有发现Python 有现成的类似功能模块,所以昨天写了个简单的 strip_tags 但还有些问题,今天应用到采集上时进行了部分功能的完善,

1. 对自闭和标签处理

2. 以及对标签参数的过滤


def strip_tags(html, save_tags=None, save_attrs=None):    result = []    start = []    data = []    # 特殊的自闭和标签, 按 HTML5 的规则, 如 <br> <img  alt="Python 清理HTML标签类似PHP的strip_tags函数功能(二)" > <wbr> 不再使用 /> 结尾    special_end_tags = [        'area', 'base', 'br', 'col', 'embed', 'hr',        'img', 'input', 'keygen', 'link', 'meta', 'param',        'source', 'track', 'wbr'    ]    def starttag(tag, attrs):        if tag not in save_tags:            return        start.append(tag)        my_attrs = []        if attrs:            for attr in attrs:                if save_attrs and attr[0] not in save_attrs:                    continue                my_attrs.append(attr[0] + '="' + attr[1] + '"')            if my_attrs:                my_attrs = ' ' + (' '.join(my_attrs))            else:                my_attrs = ''        else:            my_attrs = ''        result.append('')    def endtag(tag):        if start and tag == start[len(start) - 1]:            # 特殊自闭和标签按照HTML5规则不加反斜杠直接尖括号结尾            if tag not in special_end_tags:                result.append('' + tag + '>')    parser = HTMLParser()    parser.handle_data = result.append    if save_tags:        parser.handle_starttag = starttag        parser.handle_endtag = endtag    parser.feed(html)    parser.close()    for i in range(0, len(result)):        tmp = result[i].rstrip('\n')        tmp = tmp.lstrip('\n')        if tmp:            data.append(tmp)    return ''.join(data)</wbr>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:有关PHP分页显示的问题Next article:unlink()