python模块学习---HTMLParser(解析HTML文档元素)

来源:互联网 发布:tripmode mac 编辑:程序博客网 时间:2024/06/06 18:34

HTMLParser是Python自带的模块,使用简单,能够很容易的实现HTML文件的分析。

本文主要简单讲一下HTMLParser的用法.


使用时需要定义一个从类HTMLParser继承的类,重定义函数:
handle_starttag( tag, attrs)
handle_startendtag( tag, attrs)
handle_endtag( tag)

来实现自己需要的功能。

tag是的html标签,attrs是 (属性,值)元组(tuple)的列表(list)。
HTMLParser自动将tag和attrs都转为小写。

下面给出的例子抽取了html中的所有链接:(在PYTHON3.3版本中)

 

  1. from html.parser import HTMLParser  
  2. class MyHTMLParser(HTMLParser):   
  3.     def __init__(self):   
  4.         HTMLParser.__init__(self)   
  5.         self.links = []   
  6.     def handle_starttag(self, tag, attrs):   
  7.         #print "Encountered the beginning of a %s tag" % tag   
  8.         if tag == "a":   
  9.             if len(attrs) == 0:   
  10.                 pass   
  11.             else:   
  12.                 for (variable, value) in attrs:   
  13.                     if variable == "href":   
  14.                         self.links.append(value)   
  15.                      
  16. if __name__ == "__main__":   
  17.     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> """   
  18.     hp = MyHTMLParser()   
  19.     hp.feed(html_code)   
  20.     hp.close()   
  21.     print(hp.links)  


运行结果为:

 

['www.google.com', 'www.pythonclub.org', 'www.sina.com.cn']

---------------------------------------------

显示HTML中<a>标签之间的文字:

 

  1. from html.parser import HTMLParser  
  2.   
  3. 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">世纪佳缘'''  
  4.   
  5. class hp(HTMLParser):  
  6.     a_text = False  
  7.       
  8.     def handle_starttag(self,tag,attr):  
  9.         if tag == 'a':  
  10.             self.a_text = True  
  11.             #print (dict(attr))  
  12.               
  13.     def handle_endtag(self,tag):  
  14.         if tag == 'a':  
  15.             self.a_text = False  
  16.               
  17.     def handle_data(self,data):  
  18.         if self.a_text:  
  19.             print (data)  
  20.               
  21. yk = hp()  
  22. yk.feed(page)  
  23. yk.close()  


运行结果如下:

 

京东商城
乐淘网上鞋城
拉手团购
亚马逊
凡客诚品
世纪佳缘

注:在eclipse中的pydev中调试,记得中文编码问题,在项目中右键改编码为utf-8

0 0
原创粉丝点击