HTMLParser介绍
2015-07-29 22:24
429 查看
使用时需要新建一个继承自HTMLParser的类
一个完整的类块如下:
一些例子:
运行结果:[‘www.google.com’, ‘www.pythonclub.org’, ‘www.sina.com.cn’]
运行结果:
京东商城
乐淘网上鞋城
拉手团购
亚马逊
凡客诚品
世纪佳缘
整理自:http://www.cnblogs.com/mfryf/p/3691563.html
后续将有自己的添加…
一个完整的类块如下:
[code]class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) #需要实现以下方法(可选) #tag是html标签,attrs是(variable,value)的元组的列表 #处理开始结束标签,如<img /> def handle_startendtag(self,tag,attrs): pass #处理开始标签 def handle_starttag(self,tag,attrs): pass #处理结束标签,如</XX> def handle_endtag(self,tag): pass #处理特殊字符,以开头的,一般为内码表示的字符 def handle_charref(self,name): pass #处理一些特殊的字符,以&开头的 def handle_entityref(self,name): pass #处理数据,<XX>data<XX> def handle_data(self,data): pass #处理注释 def handle_comment(self,data): pass #处理以 <! 开头的 def handle_decl(): pass #处理形如<?instruction>的东西 def handle_pi(): pass
一些例子:
[code]from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.links = [] def handle_starttag(self, tag, attrs): #print "Encountered the beginning of a %s tag" % tag if tag == "a": if len(attrs) == 0: pass else: for (variable, value) in attrs: if variable == "href": self.links.append(value) if __name__ == "__main__": html_code = """ <a href="www.google.com"> google.com</a> <A Href="www.pythonclub.org"> PythonClub </a> <A HREF = "www.sina.com.cn"> Sina </a> """ hp = MyHTMLParser() hp.feed(html_code) hp.close() print(hp.links)
运行结果:[‘www.google.com’, ‘www.pythonclub.org’, ‘www.sina.com.cn’]
[code]from html.parser import HTMLParser page ='''''<sada>啊啊啊</sada><a href="http://click.union.360buy.com/JdClick /?unionId=75" class="f1" style="padding-left:13px; padding-right:14px">京东商城</a></td><td><a href="http://www.letao.com /?source=hao123" class="f1">乐淘网上鞋城</a></td><td><a href="http://www.lashou.com/cl_today/w_3001" class="f2">拉手团购</a></td><td><a href="http://www.amazon.cn/?tag=2009hao123famousdaohang" class="f2">亚马逊</a></td><td><a href="http://www.vancl.com/?source=hao123mp" class="f1">凡客诚品</a></td><td><a href="http://reg.jiayuan.com/st/?id=3237&url=/st /main.php" class="f1">世纪佳缘''' class hp(HTMLParser): a_text = False def handle_starttag(self,tag,attr): if tag == 'a': self.a_text = True #print (dict(attr)) def handle_endtag(self,tag): if tag == 'a': self.a_text = False def handle_data(self,data): if self.a_text: print (data) yk = hp() yk.feed(page) yk.close()
运行结果:
京东商城
乐淘网上鞋城
拉手团购
亚马逊
凡客诚品
世纪佳缘
整理自:http://www.cnblogs.com/mfryf/p/3691563.html
后续将有自己的添加…
相关文章推荐
- HTML元素的基本特性
- 7_29_html_表单和框架
- html 7.29
- sublime Html快捷键大全
- XHTML插入表格状数据
- 页面制作 Chapter 3--HTML
- html 1:1比例显示
- html 文档类型DTD与浏览器怪异模式
- Html基础知识
- html中设置锚点定位的几种常见方法
- html标签<一>
- HTML <img> 标签
- html meta标签常用属性整理
- HTML 背景颜色半透明
- html加载顺序、onload、JQ.ready()
- CHtml::link() CHtml::ajaxLink() CHtml::button() CHtml::textField() CHtml::listDa
- 静态Web开发 HTML
- 将PDF转换成html的操作步骤
- 【HTML学习】第六章 为Web应用程序铺平道路
- asp.net c#过滤html代码,净化DIV SPAN等