среда, 22 сентября 2010 г.

(ИМХО) лучшее решение для чистки html от мусора


# -*- coding:utf-8 -*-

from lxml.html.clean import Cleaner
import re

class CleanEmpty(Cleaner):

    white = re.compile('[\r\n\t]+')

    def __call__(self, doc):
        super(CleanEmpty, self).__call__(doc)

        empty = []
        for el in doc.iter():
            if el.text:
                el.text = self.white.sub('', el.text.strip()).replace('  ', ' ')
            elif not list(el):
                empty.append(el)
            if el.tail:
                el.tail = ''
        for el in empty:
            el.drop_tag()

def clean_html(buf):

    c = CleanEmpty(
        allow_tags=('html','body', 'a', 'p', 'img', 'h2', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'strong', 'em', 'sup', 'sub', 'ul', 'ol', 'li'),
        scripts=False,
        style=True,
        comments=False,
        page_structure=False,
        remove_unknown_tags=False)
    return c.clean_html(buf)

if __name__ == '__main__':
    import sys
    print clean_html(open(sys.argv[1]).read().decode('utf-8'))[12:-14].encode('utf-8')

Комментариев нет:

Отправить комментарий