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