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

Python 中可以使用 html.parser 模块中的 HTMLParser 类来解析 HTML 内容。它是一个内置的轻量级解析器,适合处理简单的 HTML 结构,无需安装第三方库。
你需要自定义一个类,继承 HTMLParser,并重写特定的方法来捕获标签、数据和属性。
示例代码:from html.parser import HTMLParser
<p>class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(f"开始标签: {tag}, 属性: {attrs}")</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">def handle_endtag(self, tag):
print(f"结束标签: {tag}")
def handle_data(self, data):
if data.strip(): # 忽略空白字符
print(f"文本内容: {data}")html_content = """ <div class="example"> <p id="para1">这是一个段落。</p> <a href="https://example.com">链接> </div> """
parser = MyHTMLParser() parser.feed(html_content)
以下是几个关键的回调方法,用于提取不同部分的信息:
如果你想提取页面中所有的超链接和地址,可以这样写:
立即学习“Python免费学习笔记(深入)”;
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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('<a href="https://www.php.cn/link/c7c8c6f06ba0b5edd19e56048a7c4ec1">Google>') print(parser.links) # 输出: [('https://www.php.cn/link/c7c8c6f06ba0b5edd19e56048a7c4ec1', 'Google')]
虽然 HTMLParser 足够简单场景使用,但有几点需要注意:
对于复杂网页抓取任务,建议结合 requests + BeautifulSoup;但如果只是轻量解析且不想引入外部依赖,HTMLParser 是个不错的选择。
基本上就这些,掌握这几个核心方法就能应对大多数基础解析需求了。
以上就是python中htmlparser解析html的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号