HTMLParser.handle_pi(data)#处理命令,
data 参数包含整个的处理命令.例如 <?proc color=’red'> ,该方法应写成 handle_pi("proc color='red'")
下面是处理A标签的例子:
#!/usr/bin/python
#encoding='utf-8'
import htmllib,urllib,formatter,string
'''
import chardet,sys
type = sys.getdefaultencoding()
'''
class GetLinks(htmllib.HTMLParser): #从HTMLParser类中继承
def __init__(self): #初始化的时候调用,将links设置为空。这里的links为字典结构
self.links = {} #存放地址->链接的字典
f = formatter.NullFormatter()#将传输过来的数据不做处理,格式化为数据流
htmllib.HTMLParser.__init__(self, f)
def anchor_bgn(self, href, name, type): #锚点标签开始的时候处理
self.save_bgn()
self.link = href
def anchor_end(self): #锚点标签结束的时候处理
text = string.strip(self.save_end()) #去掉A标签保留A标签的信息
if self.link and text:
self.links[text] = self.link#self.links.get(text, []) + [self.link]
#print self.links
#exit()
fp = urllib.urlopen("http://www.baidu.com") #打开指定的URL
data = fp.read()
fp.close()
linkdemo = GetLinks() #实例化一个LinkDemo对象
linkdemo.feed(data) #给HTMLParser喂食
linkdemo.close()
for href, link in linkdemo.links.items(): #打印相关的信息
print href, "=>", link
输出:
hao123 => http://www.hao123.com
搜索设置 => /gaoji/preferences.html
使用百度前必读 => /duty/
加入百度推广 => http://e.baidu.com/?refer=888
还有个例子:
#!/usr/bin/python
#encoding=utf-8
import HTMLParser
class MyParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
def handle_starttag(self, tag, attrs):
# 这里重新定义了处理开始标签的函数
if tag == 'a':
# 判断标签<a>的属性
for name,value in attrs:
if name == 'href':
print value
if __name__ == '__main__':
a = '<html><head><title>test</title><body><a href="http: //www.163.com">链接到163</a><a href="http://www.focus.cn">焦点</a></body></html>'
my = MyParser()
# 传入要分析的数据,是html的。
my.feed(a)