【问题标题】:Why HTMLParser ignores start tags in non-strict mode?为什么 HTMLParser 在非严格模式下会忽略开始标签?
【发布时间】: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


【解决方案1】:

这是 python 3.2.2(和其他)中的一个错误,请参阅http://bugs.python.org/issue13273 了解详细信息和快速修复。在 3.2.3 中已修复。

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2014-05-16
    • 2011-03-09
    • 2012-12-11
    • 2018-05-13
    相关资源
    最近更新 更多