HTMLParser HTML文档解析器 HTMLParser是Python的一个内置模块,用于解析HTML文档。它提供了一个解析器类,可以用来遍历HTML文档树,并提取出所需的信息。 使用HTMLParser,可以将HTML文档解析成一系列的标签、文本和注.. 已关注

提示信息
HTMLParser HTML文档解析器
HTMLParser是Python的一个内置模块,用于解析HTML文档。它提供了一个解析器类,可以用来遍历HTML文档树,并提取出所需的信息。 使用HTMLParser,可以将HTML文档解析成一系列的标签、文本和注释,并通过重写解析器类的方法来处理这些元素。 以下是HTMLParser常用的方法: - handle_starttag(tag, attrs):处理开始标签。在解析器遇到一个开始标签时调用,传入标签名和属性列表。 - handle_endtag(tag):处理结束标签。在解析器遇到一个结束标签时调用,传入标签名。 - handle_data(data):处理文本数据。在解析器遇到文本数据时调用,传入文本内容。 - handle_comment(data):处理注释。在解析器遇到注释时调用,传入注释内容。 以下是一个示例,演示了如何使用HTMLParser解析HTML文档: ```python 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) def handle_comment(self, data): print("Encountered a comment:", data) parser = MyHTMLParser() html = """ Sample HTML

Hello, world!

This is a sample HTML document.

""" parser.feed(html) ``` 运行上述代码,输出结果如下: ``` Encountered a start tag: html Encountered a start tag: head Encountered a start tag: title Encountered some data: Sample HTML Encountered an end tag: title Encountered an end tag: head Encountered a start tag: body Encountered a start tag: h1 Encountered some data: Hello, world! Encountered an end tag: h1 Encountered a start tag: p Encountered some data: This is a sample HTML document. Encountered an end tag: p Encountered a comment: This is a comment Encountered an end tag: body Encountered an end tag: html ``` 可以看到,解析器按照HTML文档的结构,依次调用相应的方法,并输出相应的结果。
  • 1
  • 文章
  • 0
  • 关注人数
×

小程序:无忧编码

手机扫一扫

 

Copyright © 2020 京ICP备16023093号-6   京公网安备 11010802031226号