Python内置html.parser模块的HTMLParser类可用于解析HTML。通过继承该类并重写handle_starttag、handle_endtag、handle_data等方法,可提取标签、属性和文本内容。例如LinkExtractor类可提取超链接地址与锚文本。适用于结构良好的HTML片段,但不修复 malformed HTML,无CSS选择器支持,适合轻量级任务。

Python 中可以使用 html.parser 模块中的 HTMLParser 类来解析 HTML 内容。它是一个内置的轻量级解析器,适合处理简单的 HTML 结构,无需安装第三方库。
基本用法:继承 HTMLParser 类
你需要自定义一个类,继承 HTMLParser,并重写特定的方法来捕获标签、数据和属性。
示例代码:from html.parser import HTMLParserclass MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print(f"开始标签: {tag}, 属性: {attrs}")
def handle_endtag(self, tag): print(f"结束标签: {tag}") def handle_data(self, data): if data.strip(): # 忽略空白字符 print(f"文本内容: {data}")使用示例
html_content = """
"""这是一个段落。
https://example.com">链接>parser = MyHTMLParser() parser.feed(html_content)
常用处理方法说明
以下是几个关键的回调方法,用于提取不同部分的信息:
- handle_starttag(tag, attrs):当遇到开始标签时调用,tag 是标签名,attrs 是 (name, value) 元组组成的列表。
- handle_endtag(tag):当遇到结束标签时调用。
- handle_data(data):处理标签之间的文本内容。
- handle_comment(data):处理 HTML 注释(可选重写)。
提取特定信息:比如所有链接
如果你想提取页面中所有的超链接和地址,可以这样写:
立即学习“Python免费学习笔记(深入)”;
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
attrs_dict = dict(attrs)
href = attrs_dict.get('href')
text = "" # 初始化
self.current_href = href
self.capture_text = True
else:
self.capture_text = False
def handle_data(self, data):
if self.capture_text:
self.links.append((self.current_href, data.strip()))
示例使用
parser = LinkExtractor()
parser.feed('https://www.php.cn/link/c7c8c6f06ba0b5edd19e56048a7c4ec1">Google>')
print(parser.links) # 输出: [('https://www.php.cn/link/c7c8c6f06ba0b5edd19e56048a7c4ec1', 'Google')]
注意事项与局限性
虽然 HTMLParser 足够简单场景使用,但有几点需要注意:
- 不自动修复 malformed HTML(如未闭合标签),可能解析出错。
- 相比 BeautifulSoup 或 lxml,功能较弱,没有 CSS 选择器支持。
- 适用于结构清晰、格式良好的 HTML 片段。
对于复杂网页抓取任务,建议结合 requests + BeautifulSoup;但如果只是轻量解析且不想引入外部依赖,HTMLParser 是个不错的选择。
基本上就这些,掌握这几个核心方法就能应对大多数基础解析需求了。











