在學習python的過程當中,作練習,解析https://www.python.org/events/python-events/ HTML文件,輸出Python官網發佈的會議時間、名稱和地點。html
對html的解析是網頁抓取的基礎,分析抓取的結果找到本身想要的內容或標籤以達到抓取的目的。 python
HTMLParser是python用來解析html的模塊。它能夠分析出html裏面的標籤、數據等等,是一種處理html的簡便途徑。 HTMLParser採用的是一種事件驅動的模式,當HTMLParser找到一個特定的標記時,它會去調用一個用戶定義的函數,以此來通知程序處理。它主要的用戶回調函數的命名都是以handler_開頭的,都是HTMLParser的成員函數。當咱們使用時,就從HTMLParser派生出新的類,而後從新定義這幾個以handler_開頭的函數便可。函數
代碼以下:學習
#coding:utf-8 from HTMLParser import HTMLParser from htmlentitydefs import name2codepoint import os,string,urllib2 ''' HTMLParser的成員函數: 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>的東西 ''' class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.flag=None def handle_starttag(self, tag, attrs): if tag == 'h3' and attrs.__contains__(('class', 'event-title')): print '\n\n會議主題:', self.flag=True #在須要打印的塊中設置標識 elif tag == 'time': print '\n會議時間:', self.flag=True elif tag == 'span' and attrs.__contains__(('class', 'event-location')): print '\n會議地址:', self.flag=True def handle_endtag(self, tag): if tag in('h3','time','span'): self.flag=None #print('</%s>' % tag) def handle_startendtag(self, tag, attrs): #print('<%s/>' % tag) pass def handle_data(self, data): if self.flag: #判斷是須要的值纔打印 print('%s' % data), #末尾加逗號打印不換行 def handle_comment(self, data): #print('<!-- -->') pass def handle_entityref(self, name): if name == 'ndash': print '至', else: pass def handle_charref(self, name): #print('&#%s;' % name) pass #f=open('python.html','r++') #data=f.read() #f.close() pyhtml=urllib2.urlopen('https://www.python.org/events/python-events/').read() parser = MyHTMLParser() parser.feed(pyhtml)
執行結果:url
[root@study lzc]# python h.py 會議主題: PyCon US 2016 會議時間: 28 May 至 06 June 2016 會議地址: Portland, Oregon, United States 會議主題: PyConTW 2016 in Taiwan 會議時間: 03 June 至 06 June 2016 會議地址: Academia Sinica, 128 Academia Road, Section 2, Nankang, Taipei 11529, Taiwan 會議主題: GeoPython 2016 會議時間: 22 June 至 25 June 2016 會議地址: University of Applied Sciences and Arts Northwestern Switzerland, Basel, Switzerland 會議主題: PyCon Singapore 2016 會議時間: 23 June 至 26 June 2016 會議地址: National University of Singapore, School of Computing, Computing 1, 13 Computing Drive, Singapore 117417, Republic of Singapore 會議主題: PyGotham 2016 會議時間: 16 July 至 18 July 2016 會議地址: New York, NY, USA 會議主題: EuroPython 2016 會議時間: 17 July 至 25 July 2016 會議地址: ECC, Bilbao, Basque Country, Spain 會議主題: PyData Berlin 2016 會議時間: 20 May 至 22 May 2016 會議地址: Kosmos, Karl-Marx-Allee 131a, 10243 Berlin, Germany 會議主題: SciPy Latin America 2016 會議時間: 16 May 至 21 May 2016 會議地址: Florianópolis - State of Santa Catarina, Brazil