python中htmlparser解析html

2025-12-01 0 90,195

说明

1、htmlparser提供了一种方便简洁的处理html文件的方法。

它根据树形结构将html页面中的标签分析成一个节点,一种类型的节点对应一个类,通过调用它可以轻松访问标签中的内容。

2、html本质上是xml的子集,但是html的语法没有html严格,不能用标准的DOM或者SAX来分析html。

实例

from html.parser import HTMLParser
from html.entities import name2codepoint
 
class MyHTMLParser(HTMLParser):
 
    def handle_starttag(self, tag, attrs):
        print('<%s>' % tag)
 
    def handle_endtag(self, tag):
        print('' % tag)
 
    def handle_startendtag(self, tag, attrs):
        print('<%s/>' % tag)
 
    def handle_data(self, data):
        print(data)
 
    def handle_comment(self, data):
        print('')
 
    def handle_entityref(self, name):
        print('&%s;' % name)
 
    def handle_charref(self, name):
        print('&#%s;' % name)
 
parser = MyHTMLParser()
parser.feed('''



    

Some html HTML tutorial...
END

''')   //test结果                   

Some html  HTML tutorial...
END

   

以上就是python中htmlparser解析html,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python中htmlparser解析html https://www.zhiup.top/1083.html

相关