url过滤器

来源:互联网 发布:json数组长度 编辑:程序博客网 时间:2024/06/14 22:55
先上代码
# encoding:utf-8  import sys    reload(sys)  sys.setdefaultencoding('utf8')   import requestsfrom HTMLParser import HTMLParserclass MyHtmlParser(HTMLParser):def __init__(self):HTMLParser.__init__(self)self.link = []def handle_starttag(self, tag, attrs):if tag == 'a':if len(attrs) == 0:passelse:for (attr, value) in attrs:if attr == 'href':self.link.append(value)def SaveToFile(filename, content):f = open(filename, 'a+')try:f.write(content)except Exception, e:print Exception,":", ef.write(content)f.close()if __name__ == "__main__":r = requests.get('http://www.xysay.com')SaveToFile('HtmlSet.txt', r.content.encode('utf-8'))parser = MyHtmlParser()parser.feed(r.content.encode('utf-8'))parser.close()print parser.linkSaveToFile('urlSet.txt', str(parser.link))

用到了Requests,这是个非内置模块,所以要自己去下载安装,具体方法google。 为了实现过滤url的功能要用到HTMLParser这个模块,需要动手自己写一个HTMLParser的子类并且将handle_tagstart函数重载成能实现你想要的功能的样子,这个类里还有两个函数式handle_data和handle_tagend,由于在url过滤中没用到所以就无需重载了。

图示效果

0 0