#小练习 使用字典保存HTMLParser解析的数据
2013-11-08 20:51
393 查看
#coding:utf-8
import HTMLParser
class myhp(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.d={}
self.tag=None
self.content=None
def handle_starttag(self,tag,attr):
#注意:tag不区分大小写,此时也可以解析 <A 标签
if tag=='a':
for href,link in attr:
if href.lower()=="href":
self.tag='a'
self.content=link
def handle_data(self,data):
if self.tag=='a' and len(data.strip()):
self.d[data.strip()] =self.content
# 遇到 </a ,设置self.tag =None
def handle_endtag(self,tag):
if tag=='a':
self.tag=None
if __name__ == "__main__":
html_code='''
<a href="www.google.com"> goolge.com </a>
<AB href="www.sohu.com.cn"> sohu.com </a>
<A Href="www.pythonclub.org">PythonClub </a>
<A HREF='www.sina.com.cn'> sina </a>
'''
m = myhp()
m.feed(html_code)
print m.d
m.close()
import HTMLParser
class myhp(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.d={}
self.tag=None
self.content=None
def handle_starttag(self,tag,attr):
#注意:tag不区分大小写,此时也可以解析 <A 标签
if tag=='a':
for href,link in attr:
if href.lower()=="href":
self.tag='a'
self.content=link
def handle_data(self,data):
if self.tag=='a' and len(data.strip()):
self.d[data.strip()] =self.content
# 遇到 </a ,设置self.tag =None
def handle_endtag(self,tag):
if tag=='a':
self.tag=None
if __name__ == "__main__":
html_code='''
<a href="www.google.com"> goolge.com </a>
<AB href="www.sohu.com.cn"> sohu.com </a>
<A Href="www.pythonclub.org">PythonClub </a>
<A HREF='www.sina.com.cn'> sina </a>
'''
m = myhp()
m.feed(html_code)
print m.d
m.close()
相关文章推荐
- #小练习 使用字典保存HTMLParser解析的数据 分类: python 小练习 HTMLParser 2013-11-08 20:51 574人阅读 评论(0) 收藏
- #小练习 解析HTML文件并使用字典保存链接 分类: HTMLParser python 小练习 2013-11-11 12:06 267人阅读 评论(0) 收藏
- #小练习 解析HTML文件并使用字典保存链接
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- django中使用mongoengine保存字典结构的数据到数据库。
- 【android, 3】3.操作数据保存到rom,sd卡上,sharedpreference的使用,pul解析xml
- C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- SBJson 框架使用2 SBJson解析数据 解析字典,数组
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- Android中使用xml保存数据(xml文件序列化)及使用pull解析xml文件
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- 使用了类和字典来保存数据 查询数据
- C++文本查询程序 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果