处理HTML以删除和关闭Python中的打开标记

时间:2012-08-22 18:26:35

标签: python html html-parsing jinja2

我正在尝试使用HTMLParser在Python中处理HTML而不关闭标记或使用无效的结束标记:

项:

<div>
  <p>foo 
</div>
bar</span>

输出:(关闭打开标签并打开错误的关闭)

<div>
  <p>foo</p>
</div>
<span>bar</span>

或者甚至:(在没有立即打开和关闭所有打开的标签的情况下删除闭包)

<div>
  <p>foo bar</p>
</div>

我的代码只会关闭打开的代码,但无法在HTMLParser的循环中编辑HTML。

from HTMLParser import HTMLParser

singleton_tags = [
  'area','base','br','col','command','embed','hr',
  'img', 'input','link','meta','param','source'
]

class HTMLParser_(HTMLParser):

    def __init__(self, *args, **kwargs):
        HTMLParser.__init__(self, *args, **kwargs)
        self.open_tags = []

    # Handle opening tag
    def handle_starttag(self, tag, attrs):
        if tag not in singleton_tags:
            self.open_tags.append(tag)

    # Handle closing tag
    def handle_endtag(self, tag):
        if tag not in singleton_tags:
            self.open_tags.pop()

def close_tags(text):
    parser = HTMLParser_()

    # Mounts stack of open tags
    parser.feed(text)

    # Closes open tags
    text += ''.join('</%s>'%tag for tag in parser.open_tags)

    return text

1 个答案:

答案 0 :(得分:2)

我建议调查BeautifulSoup。它是我用过的最好的HTML解析器(适用于任何语言),并且在Python中使用HTML非常容易。

有一个prettify函数可能对您有用。查看标题为Printing a Document的部分。