python中htmlparser解析html

423次阅读
没有评论

python中htmlparser解析html

htmlparser解析html说明

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

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

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

htmlparser解析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,希望对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-04-05发表,共计1090字。
新手QQ群:570568346,欢迎进群讨论 Python51学习