【发布时间】:2012-05-01 14:04:21
【问题描述】:
我基于 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()
因此,对于严格模式和非严格模式,我得到了两个不同的结果。 严格:
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 喜欢名为
my_parser而不是myParser的变量。 -
无法重现此(3.2.3,Ubuntu 64 位)。
-
可能是 3.2.3 中修复的错误,但我认为更可能是用户错误。再试一次。
-
我可以用 Python 3.2.2 重现这个,看起来像这个错误:bugs.python.org/issue13273
-
已通过升级到 3.2.3 版本修复。非常感谢大家的快速帮助。
标签: python python-3.x html-parsing