HTMLParser に基づいて単純なパーサーを作成しました。
from html.parser import HTMLParser
class MyParser(HTMLParser):
def __init__(self, strict = True):
super().__init__(strict)
def handle_starttag(self, tag, attrs):
print('Start tag: ', tag)
def handle_endtag(self, tag):
print('End tag ', tag)
次に、次の例を厳密モードと非厳密モードで解析してみます (HTMLParser コンストラクターで strict=True または strict=False を渡すことにより):
source = '''
<!DOCTYPE html>
<html>
<head>
<title>Hello HTML</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
'''
#myParser = MyParser(True) # strict
myParser = MyParser(False) # non-strict
myParser.feed(source)
myParser.close()
その結果、厳密モードと非厳密モードで 2 つの異なる結果が得られました。厳しい:
Start tag: html
Start tag: head
Start tag: title
End tag title
End tag head
Start tag: body
Start tag: p
End tag p
End tag body
End tag html
非厳密:
End tag title
End tag head
End tag p
End tag body
End tag html
非厳密モードで HTMLParser が開始タグを無視するのはなぜですか? 開始タグを省略せずに非厳密モードで HTMLParser を使用するには?