在学习python的过程中,做练习,解析https://www.python.org/events/python-events/ HTML文件,输出Python官网发布的会议时间、名称和地点。

对html的解析是网页抓取的基础,分析抓取的结果找到自己想要的内容或标签以达到抓取的目的。   

    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)

 

执行结果:

[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

 

posted on 2016-05-24 16:36  lzc_jack  阅读(696)  评论(0编辑  收藏  举报