使用python解析xml成对应的html示例分享

时间:2022-05-05 21:02:27 

SAX将dd.xml解析成html。当然啦,如果得到了xml对应的xsl文件可以直接用libxml2将其转换成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('''<html>\n<head>\n<title> RSS-''')

    def endChannel(self):
       self.fout.write('''
                    <tr><td height="20"></td></tr>
                    </table>
                    </center>
                    <script>
    function  GetTimeDiff(str)
    {
     if(str == '')
     {
      return '';
     }

     var pubDate = new Date(str);
     var nowDate = new Date();
     var diffMilSeconds = nowDate.valueOf()-pubDate.valueOf();
     var days = diffMilSeconds/86400000;
     days = parseInt(days);

     diffMilSeconds = diffMilSeconds-(days*86400000);
     var hours = diffMilSeconds/3600000;
     hours = parseInt(hours);

     diffMilSeconds = diffMilSeconds-(hours*3600000);
     var minutes = diffMilSeconds/60000;
     minutes = parseInt(minutes);

     diffMilSeconds = diffMilSeconds-(minutes*60000);
     var seconds = diffMilSeconds/1000;
     seconds = parseInt(seconds);

     var returnStr = "±±&frac34;&copy;·&cent;&sup2;&frac14;&Ecirc;±&frac14;&auml;&pound;&ordm;" + pubDate.toLocaleString();

     if(days > 0)
     {
      returnStr = returnStr + "&nbsp;&pound;¨&frac34;à&Agrave;&euml;&Iuml;&Ouml;&Ocirc;&Uacute;" + days + "&Igrave;ì" + hours + "&ETH;&iexcl;&Ecirc;±" + minutes + "·&Ouml;&Ouml;&Oacute;&pound;&copy;";
     }
     else if (hours > 0)
     {
      returnStr = returnStr + "&nbsp;&pound;¨&frac34;à&Agrave;&euml;&Iuml;&Ouml;&Ocirc;&Uacute;" + hours + "&ETH;&iexcl;&Ecirc;±" + minutes + "·&Ouml;&Ouml;&Oacute;&pound;&copy;";
     }
     else if (minutes > 0)
     {
      returnStr = returnStr + "&nbsp;&pound;¨&frac34;à&Agrave;&euml;&Iuml;&Ouml;&Ocirc;&Uacute;" + minutes + "·&Ouml;&Ouml;&Oacute;&pound;&copy;";
     }

     return returnStr;

    }

    function GetSpanText()
    {
     var pubDate;
     var pubDateArray;
     var spanArray = document.getElementsByTagName("span");

     for(var i = 0; i < spanArray.length; i++)
     {
      pubDate = spanArray[i].innerHTML;
      document.getElementsByTagName("span")[i].innerHTML = GetTimeDiff(pubDate);   
     }
    }

    GetSpanText();
   </script>
                </body>
                </html>
                ''')
       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('''
                        <tr bgcolor="#eeeeee">\n<td style="padding-top:5px;padding-left:5px;" height="30">\n<B>
                    ''')

    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('''
                </title>\n</head>\n<body>\n<center>\n
                <script>\n

                        function copyLink()
                        {
                                clipboardData.setData("Text",window.location.href);
                                alert("RSS&Aacute;&acute;&frac12;&Oacute;&Ograve;&Ntilde;&frac34;&shy;&cedil;&acute;&Ouml;&AElig;&micro;&frac12;&frac14;&ocirc;&Igrave;ù°&aring;");
                        }

                        function subscibeLink()
                        {
                                var str = window.location.pathname;
                                while(str.match(/^\//))
                                {
                                        str = str.replace(/^\//,"");
                                }
                                window.open("http://rss.sina.com.cn/my_sina_web_rss_news.html?url=" + str,"_self");

                        }
                        </script>\n
                <table width="750" cellpadding="0" cellspacing="0">\n
                <tr>\n
                <td align="right" style="padding-right:15px;" valign="bottom">\n
            ''')

        if self.item:
            self.title = self.temp
            self.temp = ''
            self.fout.write(self.title.encode('gb2312'))
            self.fout.write('''
                        </B>
                        </td>
                        </tr>
                        <tr bgcolor="#eeeeee">
                        <td style="padding-left:5px;">
                        ''')

    def startImage(self):
        self.imagein = True

    def endImage(self):
        self.imagein = False

    def startLink(self):
        if self.imagein:
            self.fout.write('''<A href=" ''')

           
    def endLink(self):
        self.link = self.temp
        self.temp = ''
        if self.imagein:
            self.fout.write(self.link.encode('gb2312'))
            self.fout.write('''" target="_blank">\n ''')
        elif self.item:
            #self.link = self.temp
            pass
        else:
            self.fout.write(self.link)
            self.fout.write(''' " target="
      _blank
     "> ''')
            self.fout.write(self.title.encode('gb2312'))
            self.fout.write(''' </A></B></td>
                            </tr>
                            <tr><td colspan="2" align="center">
                            ''')
            self.fout.write(self.description.encode('gb2312'))
            self.fout.write('''
                        </td></tr>
                        <tr style="font-size:12px;" bgcolor="#eeeeff"><td colspan="2" style="font-size:14px;padding-top:5px;padding-bottom:5px;"><b><a href="javascript:copyLink();">&cedil;&acute;&Ouml;&AElig;&acute;&Euml;&Ograve;&sup3;&Aacute;&acute;&frac12;&Oacute;</a>                <a href="javascript:subscibeLink();">&Icirc;&Ograve;&Ograve;&ordf;&Ccedil;&para;&Egrave;&euml;&cedil;&Atilde;&ETH;&Acirc;&Icirc;&Aring;&Aacute;&ETH;±í&micro;&frac12;&Icirc;&Ograve;&micro;&Auml;&Ograve;&sup3;&Atilde;&aelig;&pound;¨&frac14;ò&micro;&yen;&iexcl;&cent;&iquest;ì&Euml;&Ugrave;&iexcl;&cent;&Ecirc;&micro;&Ecirc;±&iexcl;&cent;&Atilde;&acirc;·&Ntilde;&pound;&copy;</a></b></td></tr>
                        </table>
                        <table width="750" cellpadding="0" cellspacing="0">
                            ''')

    def startUrl(self):
        if self.imagein:
            self.fout.write('''<IMG src=" ''')
    def endUrl(self):
        self.url = self.temp
        self.temp = ''
        if self.imagein:
            self.fout.write(self.url.encode('gb2312'))
            self.fout.write('''" border="0">\n
                            </A>
                            </td>
                            <td align="left" valign="bottom" style="padding-bottom:8px;"><B><A href="
                            ''')
        if self.item:
            #self.url = self.temp
            pass

    def defaultStart(self):
        pass
    def defaultEnd(self):
        self.temp = ''
    def startDescription(self):
        pass
    def endDescription(self):
        self.description = self.temp
        self.temp = ''
        if self.item:
            #self.fout.write('&iexcl;&iexcl;&iexcl;&iexcl;')
            self.fout.write(self.description.encode('gb2312'))

    def endGuid(self):
        self.guid = self.temp
    def endPubdate(self):
        if not self.temp.startswith('http'):
         self.pubdate = self.temp
         self.temp = ''
        else:
            self.pubdate = ''
    def startItem(self):
        self.item = True
    def endItem(self):
        self.item = False
        self.fout.write('''
                            </td>
                            </tr>
                            <tr bgcolor="#eeeeee">
                            <td style="padding-top:5px;padding-left:5px;">
                            <A href="''')
        self.fout.write(self.link)
        self.fout.write(''' " target="_blank"> ''')
        self.fout.write(self.guid)
        self.fout.write('''
                        </A>
                        </td>
                        </tr>
                        <tr bgcolor="#eeeeee">
                        <td style="padding-top:5px;padding-left:5px;padding-bottom:5px;"><span>''')
        self.fout.write(self.pubdate)
        self.fout.write('''</span></td>
                        </tr>
                        <tr height="10"><td></td></tr>''')

#程序入口
if __name__ == '__main__':
    parse('ddt.xml', Website())

标签:python,xml,html
0
投稿

猜你喜欢

  • numpy.linalg.eig() 计算矩阵特征向量方式

    2022-11-04 05:27:00
  • 用python打开摄像头并把图像传回qq邮箱(Pyinstaller打包)

    2021-04-26 22:34:55
  • 在pycharm中显示python画的图方法

    2023-07-28 09:44:39
  • windows server 2003+IIS6 出现 'ASP 不正常,因为执行请求

    2010-05-07 11:02:00
  • Python实现多张图片合成一张马赛克图片

    2022-02-15 21:09:46
  • Python注释、分支结构、循环结构、伪“选择结构”用法实例分析

    2021-01-15 14:45:25
  • 浅析php中array_map和array_walk的使用对比

    2023-09-10 22:22:28
  • MySQL数据库中的各种乱码及其解决方法

    2008-12-17 16:29:00
  • 用户体验在商业利益面前什么都不是

    2009-06-12 12:07:00
  • Thinkphp5文件包含漏洞解析

    2023-07-01 19:42:51
  • PHP未登录自动跳转到登录页面

    2023-11-15 07:39:11
  • php-fpm报502问题的解决办法

    2023-10-12 04:12:23
  • PHP面向对象程序设计子类扩展父类(子类重新载入父类)操作详解

    2023-10-15 01:41:57
  • php计算给定日期所在周的开始日期和结束日期示例

    2023-10-11 12:49:12
  • 浅谈用Python实现一个大数据搜索引擎

    2022-05-11 19:15:52
  • 互联网产品交互事件分析

    2009-10-06 15:23:00
  • Python数据正态性检验实现过程

    2022-07-10 15:46:14
  • 利用python实现简单的循环购物车功能示例代码

    2021-05-12 14:52:58
  • Python OpenCV基于霍夫圈变换算法检测图像中的圆形

    2023-11-12 05:33:36
  • PL/SQL 类型格式转换

    2009-02-26 11:07:00
  • asp之家 网络编程 m.aspxhome.com