【问题标题】:Handle HTML to remove and close open tags in Python处理 HTML 以删除和关闭 Python 中的打开标签
【发布时间】:2023-04-02 23:40:01
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: python html html-parsing jinja2


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 2015-06-24
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2011-04-09
      相关资源
      最近更新 更多