标签:
HTMLParser是Python自带的模块,使用简单,能够很容易的实现HTML文件的分析。
本文主要简单讲一下HTMLParser的用法.
使用时需要定义一个从类HTMLParser继承的类,重定义函数:
来实现自己需要的功能。
tag是的html标签,attrs是 (属性,值)元组(tuple)的列表(list).
HTMLParser自动将tag和attrs都转为小写。
下面给出的例子抽取了html中的所有链接:
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.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_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.links)
输出为:
[‘www.google.com‘, ‘www.pythonclub.org‘, ‘www.sina.com.cn‘]
如果想抽取图形链接:
<img src=‘http://www.google.com/intl/zh-CN_ALL/images/logo.gif‘ />
就要重定义 handle_startendtag( tag, attrs) 函数
直接上例子吧
import urllib2
from sgmllib import SGMLParser
class ListName(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.is_h4 = ""
self.name = []
def start_h4(self, attrs):
self.is_h4 = 1
def end_h4(self):
self.is_h4 = ""
def handle_data(self, text):
if self.is_h4 == 1:
self.name.append(text)
content = urllib2.urlopen(‘http://list.taobao.com/browse/cat-0.htm‘).read()
listname = ListName()
listname.feed(content)
for item in listname.name:
print item.decode(‘gbk‘).encode(‘utf8‘)
很简单,这里定义了一个叫做ListName的类,继承SGMLParser里面的方法。使用一个变量is_h4做标记判定html文件中的h4标签,如果遇到h4标签,则将标签内的内容加入到List变量name中。解释一下start_h4()和end_h4()函数,他们原型是SGMLParser中的
start_tagname(self, attrs)
end_tagname(self)
tagname就是标签名称,比如当遇到<pre>,就会调用start_pre,遇到</pre>,就会调用 end_pre。attrs为标签的参数,以[(attribute, value), (attribute, value), ...]的形式传回。
输出:
虚拟票务
数码市场
家电市场
女装市场
男装市场
童装童鞋
女鞋市场
男鞋市场
内衣市场
箱包市场
服饰配件
珠宝饰品
美容市场
母婴市场
家居市场
日用市场
食品/保健
运动鞋服
运动户外
汽车用品
玩具市场
文化用品市场
爱好市场
生活服务
如果有乱码,可能是与网页编码不一致,需要替换最后一句deconde()的参数,我在HK淘宝默认用的是繁体编码。各位可以copy上面的代码自己试试,把淘宝的商品目录抓下来,就是这么简单。稍微改改,就可以抽取二级分类等其他信息。
以下帖子请参考:
http://blog.csdn.net/nwpulei/article/details/7272832
标签:
原文地址:http://www.cnblogs.com/hester/p/5420605.html