background image
#fp = urllib.urlopen("http://www.baidu.com") #打开指定的 URL
#data = fp.read()
#fp.close()
data = '<html><head><title>test</title><body><a href="http: //www.163.com">
链接到 163</a><a href="http://www.focus.cn">焦点</a></body></html>'
linkdemo = GetLinks() #实例化一个 LinkDemo 对象
linkdemo.feed(data) #给 HTMLParser 喂食
linkdemo.close()
for href, link in linkdemo.links.items(): #打印相关的信息
print href, "=>", link
输出:
焦点 => http://www.focus.cn
链接到 163 => http: //www.163.com
再如:
# -* - coding: UTF-8 -* -
import htmllib, urllib, formatter, string
class GetLinks(htmllib.HTMLParser):
def __init__(self):
self.links = {}
f = formatter.NullFormatter()
htmllib.HTMLParser.__init__(self, f)
def anchor_bgn(self, href, name, type):
self.save_bgn()
if href[:4] == 'http':
self.link = href
else:
self.link = None
def anchor_end(self):
text = string.strip(self.save_end())
if self.link and text: