• 技术文章 >Python技术 >Python基础教程

    python中htmlparser解析html

    小妮浅浅小妮浅浅2021-08-30 09:39:00原创1859

    说明

    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('</%s>' % tag)
     
        def handle_startendtag(self, tag, attrs):
            print('<%s/>' % tag)
     
        def handle_data(self, data):
            print(data)
     
        def handle_comment(self, data):
            print('<!--', data, '-->')
     
        def handle_entityref(self, name):
            print('&%s;' % name)
     
        def handle_charref(self, name):
            print('&#%s;' % name)
     
    parser = MyHTMLParser()
    parser.feed('''<html>
    <head></head>
    <body>
    <!-- test html parser -->
        <p>Some <a href=\"#\">html</a> HTML tutorial...<br>END</p>
    </body></html>''')
     
    //test结果
    <html>
     
     
    <head>
    </head>
     
     
    <body>
     
     
    <!--  test html parser  -->
     
        
    <p>
    Some
    <a>
    html
    </a>
     HTML tutorial...
    <br>
    END
    </p>
     
     
    </body>
    </html>

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

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

    专题推荐:python htmlparser html
    品易云
    上一篇:python操作xml的两种方法 下一篇:python中值传递和引用传递的区别

    相关文章推荐

    • python赋值运算符支持哪些赋值• python赋值运算符是什么• python传递实参的方法• python关键字实参的使用• python导入模块的过程• python中Task封装协程• python迭代器和生成器的总结• python切片有哪些特征• python卡方检验是什么• python中T检验如何理解• python方差检验是什么意思• python操作xml的两种方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网