使用python解析xml成对应的html示例分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#---------------------------------------
# 程序:XML解析器
# 版本:01.0
# 作者:mupeng
# 日期:2013-12-18
# 语言:Python 2.7
# 功能:将xml解析成对应的html
# 注解:该程序用xml.sax模块的parse函数解析XML,并生成事件
# 继承ContentHandler并重写其事件处理函数
# Dispatcher主要用于相应标签的起始、结束事件的派发
#---------------------------------------
from xml.sax.handler import ContentHandler
from xml.sax import parse
class Dispatcher:
def dispatch(self, prefix, name, attrs=None):
mname = prefix + name.capitalize()
dname = 'default' + prefix.capitalize()
method = getattr(self, mname, None)
if callable(method): args = ()
else:
method = getattr(self, dname, None)
#args = name
#if prefix == 'start': args += attrs
if callable(method): method()
def startElement(self, name, attrs):
self.dispatch('start', name, attrs)
def endElement(self, name):
self.dispatch('end', name)
class Website(Dispatcher, ContentHandler):
def __init__(self):
self.fout = open('ddt_SAX.html', 'w')
self.imagein = False
self.desflag = False
self.item = False
self.title = ''
self.link = ''
self.guid = ''
self.url = ''
self.pubdate = ''
self.description = ''
self.temp = ''
self.prx = ''
def startChannel(self):
self.fout.write('''\n
def endChannel(self):
self.fout.write('''
''')
self.fout.close()
def characters(self, chars):
if chars.strip():
#chars = chars.strip()
self.temp += chars
#print self.temp
def startTitle(self):
if self.item:
self.fout.write('''
''')
def endTitle(self):
if not self.imagein and not self.item:
self.title = self.temp
self.temp = ''
self.fout.write(self.title.encode('gb2312'))
#self.title = self.temp
self.fout.write('''
\n\n\n
\n
\n ''') if self.item: self.title = self.temp self.temp = '' self.fout.write(self.title.encode('gb2312')) self.fout.write(''' |
|
''') def startImage(self): def endImage(self): |
|
''') self.fout.write(self.description.encode('gb2312')) self.fout.write(''' | |
¸´ÖÆ´ËÒ³Á´½Ó ÎÒҪǶÈë¸ÃÐÂÎÅÁÐ±íµ½ÎÒµÄÒ³Ã棨¼òµ¥¡¢¿ìËÙ¡¢ÊµÊ±¡¢Ãâ·Ñ£© |
''') self.fout.write(self.guid) self.fout.write(''' |
''') self.fout.write(self.pubdate) self.fout.write(''' |
上一篇: jQuery有哪些方法终止ajax请求
下一篇: 每个Java开发者需坚守的基本原则
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论