使用Python 3.2,我直接从html.parser
documentation:
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a start tag:", tag)
def handle_endtag(self, tag):
print("Encountered an end tag :", tag)
def handle_data(self, data):
print("Encountered some data :", data)
parser = MyHTMLParser(strict=False)
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
而不是获得文档中显示的结果,我得到:
Encountered some data : <html>
Encountered some data : <head>
Encountered some data : <title>
Encountered some data : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered some data : <body>
Encountered some data : <h1>
Encountered some data : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
出于某种原因,它仅在strict=False
时将某些标签视为数据BUT。如果strict=True
我得到了正确的结果:
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
答案 0 :(得分:2)
这是一个已修复的错误(http://bugs.python.org/issue13273)。实际上,当您查看http://hg.python.org/cpython/log/9ce5d456138b/Lib/html/parser.py时,会有大量有关Strict=False
问题的日志消息;几乎感觉这应该仍然被认为是beta。
如果你使用文件的最新版本(http://hg.python.org/cpython/raw-file/9ce5d456138b/Lib/html/parser.py)并使用它,至少文档中的示例再次起作用。尽管如此,我个人对于信任Strict = False目前在“关键应用程序”中工作感到有点厌倦。