您的位置:首页技术文章
文章详情页

python中HTMLParser模块知识点总结

【字号: 日期:2022-06-29 10:45:17浏览:5作者:猪猪

本章内容,我们主要来讲一下Python内置的HTML解析库HTMLParser模块,基本上也是应用于页面抓取上,假设,我们需要去收集页面上已存在的静态链接,但是页面肯定代码量都非常大,并且页面也很多,这样看来,会比较麻烦,工作量也非常大,这个时候,我们就可以用到htmlparser模块,一起来了解具体使用内容。

安装:

npm install htmlparser

htmlparser提供构造函数:

function Parser(handler) { this._handler = handler;}

HTMLParser解析HTML:

from html.parser import HTMLParserfrom html.entities import name2codepointclass 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='https://www.haobala.com/bcjs/1470.html#'>html</a> HTML tutorial...<br>END</p></body></html>’’’)

HTML本质上是XML的子集,但是HTML的语法没有XML那么严格,大家也可以尝试利用HTMLParser解析HTML。

知识点扩展:

常用方法介绍

l feed(data):主要用于接受带html标签的str,当调用这个方法时并提供相应的data时,整个实例(instance)开始执行,结束执行close()。

l handle_starttag(tag, attrs): 这个方法接收Parse_starttag返回的tag和attrs,并进行处理,处理方式通常由使用者进行覆盖,本身为空。

例如,连接的start tag是<a>,那么对应的参数tag=’a’(小写)。attrs是start tag <>中的属性,以元组形式(name, value)返回(所有这些内容都是小写)。

例如,对于<A HREF='http://www.baidu.com“>,那么内部调用形式为:handle_starttag(’a’,[(‘href’,’http://www.baidu.com)]).

l handle_endtag(tag):跟上述一样,只是处理的是结束标签,也就是以</开头的标签。

l handle_data(data):处理的是网页的数据,也就是开始标签和结束标签之间的内容。例如:<script>...</script>的省略号内容

l handle_comment(data) ,处理注释,<!-- -->之间的文本

l reset():将实例重置,包括作为参数输入的数据进行清空。

到此这篇关于python中HTMLParser模块知识点总结的文章就介绍到这了,更多相关python中HTMLParser模块是什么内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

到此这篇关于python中HTMLParser模块知识点总结的文章就介绍到这了,更多相关python中HTMLParser模块是什么内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Python 编程
相关文章: