0

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 を使用するには?

4

1 に答える 1

1

これは python 3.2.2 (およびその他) のバグでした。詳細とクイックフィックスについては、 http://bugs.python.org/issue13273を参照してください。3.2.3 で修正されています。

于 2012-05-01T23:20:47.920 に答える