0
私はHTMLParserに基づいて、単純なパーサを書いた:非厳密モードで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モードで次の例を解析しよう:
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が非strictモードで開始タグを無視するのはなぜ?開始タグを省略しない非厳密モードでHTMLParserを使用するにはどうすればよいですか?
[PEP 8](http://www.python.org/dev/peps/pep-0008/)では、 'myParser'の代わりに' my_parser'という名前の変数が好きです。 –
これを再現できません(3.2.3、Ubuntu 64-bit)。 –
私はPython 3.2.2を使用しています –