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)
然後我嘗試解析嚴格和非嚴格模式下面的例子中(通過將嚴格= True或嚴格= false在HTMLParser的構造函數):
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()
因此,對於嚴格和非嚴格模式,我得到了兩種不同的結果。 嚴格:
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而不忽略開始標記?
[PEP 8](http://www.python.org/dev/peps/pep-0008/)喜歡名爲'my_parser'而不是'myParser'的變量。 –
無法重現此(3.2.3,Ubuntu 64位)。 –
我使用Python 3.2.2 –