python模塊學習---HTMLParser(解析HTML文檔元素)


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版本中)

 

[python]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  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>標簽之間的文字:

 

[python]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  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

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

如果想抽取圖形鏈接

<img src='http://www.google.com/intl/zh-CN_ALL/images/logo.gif' />


就要重定義 handle_startendtag( tag, attrs) 函數

 

 

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

HTMLParser是python用來解 析html的模塊。它可以分析出html里面的標簽、數據等等,是一種處理html的簡便途徑。 HTMLParser采用的是一種事件驅動的模式,當HTMLParser找到一個特定的標記時,它會去調用一個用戶定義的函數,以此來通知程序處理。它主要的用戶回調函數的命名都是以handler_開頭的,都是HTMLParser的成員函數。當我們使用時,就從HTMLParser派生出新的類,然后重新定義這幾個以handler_開頭的函數即可。這幾個函數包括:
handle_startendtag 處理開始標簽和結束標簽
handle_starttag 處理開始標簽,比如<xx>
handle_endtag 處理結束標簽,比如</xx>
handle_charref 處理特殊字符串,就是以&#開頭的,一般是內碼表示的字符
handle_entityref 處理一些特殊字符,以&開頭的,比如  
handle_data 處理數據,就是<xx>data</xx>中間的那些數據
handle_comment 處理注釋
handle_decl 處理<!開頭的,比如<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
handle_pi 處理形如<?instruction>的東西


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM