python学习(解析python官网会议安排)

时间:2023-03-09 00:15:24
python学习(解析python官网会议安排)

在学习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
会议时间: May 至 June
会议地址: Portland, Oregon, United States 会议主题: PyConTW in *
会议时间: June 至 June
会议地址: Academia Sinica, Academia Road, Section , Nankang, Taipei , * 会议主题: GeoPython
会议时间: June 至 June
会议地址: University of Applied Sciences and Arts Northwestern Switzerland, Basel, Switzerland 会议主题: PyCon Singapore
会议时间: June 至 June
会议地址: National University of Singapore, School of Computing, Computing , Computing Drive, Singapore , Republic of Singapore 会议主题: PyGotham
会议时间: July 至 July
会议地址: New York, NY, USA 会议主题: EuroPython
会议时间: July 至 July
会议地址: ECC, Bilbao, Basque Country, Spain 会议主题: PyData Berlin
会议时间: May 至 May
会议地址: Kosmos, Karl-Marx-Allee 131a, Berlin, Germany 会议主题: SciPy Latin America
会议时间: May 至 May
会议地址: Florianópolis - State of Santa Catarina, Brazil