首页 > 文章列表 > python中htmlparser解析html

python中htmlparser解析html

Python HTML htmlparser
384 2022-08-07

说明

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>

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