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版本中)
- 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']
---------------------------------------------
顯示HTML中<a>標簽之間的文字:
- 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()
運行結果如下:
京東商城
樂淘網上鞋城
拉手團購
亞馬遜
凡客誠品
世紀佳緣
注:在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>的東西
