码迷,mamicode.com
首页 > 编程语言 > 详细

python模块之HTMLParser解析出URL链接

时间:2015-11-21 15:46:42      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#python模块之HTMLParser解析出URL链接
#http://www.cnblogs.com/mfryf/p/3691563.html



from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):   
    def __init__(self):   
        HTMLParser.__init__(self) #继承  
        self.links = []#links 链接
    
    def handle_starttag(self, tag, attrs):   
        #print "Encountered the beginning of a %s tag" % tag
        
        if tag == "a":   
            if len(attrs) == 0:   
                pass   
            else:   
                for variable, value in attrs:
                    if variable == "href":   
                        self.links.append(value)   

                     
if __name__ == "__main__":
    #写入一个html长字符串
    html_code = """<a href="www.google.com"> google.com</a>
<A Href="www.pythonclub.org"> PythonClub </a>
<A HREF = "www.sina.com.cn"> Sina </a>
"""   
    hp = MyHTMLParser()
    hp.feed(html_code)
    hp.close()
    #print hp.handle_starttag(‘a‘, ‘href‘)
    print hp.links #[‘www.google.com‘, ‘www.pythonclub.org‘, ‘www.sina.com.cn‘]

 

python模块之HTMLParser解析出URL链接

标签:

原文地址:http://www.cnblogs.com/dengyg200891/p/4983683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!