Python 来自 HTMLParser 的可覆盖函数

Python overidable functions from HTMLParser

我了解如何使用 HTMLParser 中的 handle_starttag,但我很困惑它的工作原理。

https://docs.python.org/3/library/html.parser.html#example-html-parser-application

文档说需要覆盖此 handle_starttag 方法,它确实按预期工作。

然而,当我检查父 class (HTMLParser) 中的定义时,定义只是 "pass".

那么 handle_starttag 是如何工作的呢?如果父定义为空,Python 如何知道 tag 是 tag 而 attrs 是属性? 如果我的问题不清楚,很乐意澄清更多。 提前致谢。

默认情况下,handle_starttag 不执行任何操作。它只是在那里被覆盖。知道什么是标签和什么是属性不是 handle_starttag 的工作;这是其他代码的工作。 handle_starttag 的默认作业。

调用handle_starttagHTMLParser求子类的方式,"hey, do you want to do anything with this start tag I just parsed"?重写 handle_starttag 是子类的响应方式 "yeah, thanks, I'll do the thing I do with start tags"。如果它没有被覆盖,它什么也不做。无论哪种方式,在调用之后,解析都会继续。