首页 > 编程语言 >Python解析XML文件

Python解析XML文件

时间:2023-05-31 15:03:09浏览次数:38  
标签:XML __ deal Python self print meituan 解析


今天学习如何利用Python来解析XML文档。


给定一个XML文件,现在我们用Python来提取里面的内容。

<deals>
    <data>
        <deal>
             <deal_id>11111111</deal_id>
             <sales_num>120</sales_num>
             <price>15.0</price>
        </deal>
    </data>
</deals>

 

Python代码:

import xml.etree.ElementTree as ET

class MeiTuanParser:
    def __init__(self):
        self.meituan_deal_set = []

    def parse(self,filepath):
        tree = ET.parse(filepath)
        root = tree.getroot()
        for data in root.iter('data'):
            deal = data.find('deal')

            meituan_deal = {}
            if deal is not None:
                try:
                    meituan_deal['deal_id'] = deal.find('deal_id').text
                except Exception, exp:
                    print "No deal id"
                try:
                    meituan_deal['sales'] = int(deal.find('sales_num').text)
                except Exception, exp:
                    print "Invalid sales number"
                try:
                    meituan_deal['price'] = float(deal.find('price').text)
                except Exception, exp:
                    print "Invalid price"

                self.meituan_deal_set.append(meituan_deal)

        return self.meituan_deal_set

if __name__ == '__main__':
    parser = MeiTuanParser()
    deals = parser.parse('meituan.xml')
    print deals

 



 

 

 

 

标签:XML,__,deal,Python,self,print,meituan,解析
From: https://blog.51cto.com/u_16146153/6386932

相关文章

  • Python 发送微信消息
    Python发送微信消息安装pipinstallitchat1、基本使用#使用微信接口给微信好友发送消息,importitchatnickname="迪丽热巴"send_message="测试消息"try:#1.自动登录方法,hotReload=True可以缓存,不用每次都登录,但是第一次执行时会出现一个二维码,需要......
  • Python 发送邮件
    Python发送邮件1、案例一(发送普通邮件)importsmtplibfromemail.mime.textimportMIMEText#发送普通邮件#POP3服务器地址:pop.qq.com#SMTP服务器地址:smtp.qq.comclassSendEmail:def__init__(self):#发送邮件的用户self.send_user=......
  • 关于F5透传问题的解析
       当负载均衡工作在透传模式中时,所防护服务器无法感知到负载均衡设备的存在,对于访问者来说,服务器的IP地址就是负载均衡设备的VIP地址。在这种模式下,当负载均衡设备收到源为访问者的IP,目的IP为本地VIP地址的报文时,会将报文根据负载均衡策略和健康状况发送给最优的服务器上,......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-2-playwright的API及其他知识
    1.简介上一篇宏哥已经将Python+Playwright的环境搭建好了,而且也简单的演示了一下三款浏览器的启动和关闭,是不是很简单啊。今天主要是把一篇的中的代码进行一次详细的注释,然后说一下playwright的API和其他相关知识点。那么首先将上一篇中的代码进行一下详细的解释。2.代码解释2.......
  • Python 函数
    函数返回多个返回值defmultiple_return_value():importdatetimed=datetime.date.today()val_1='年份为:{}'.format(d.year)val_2='月份为:{}'.format(d.month)returnval_1,val_2#只需在return关键字后跟多个值(依次用逗号分隔)val=mult......
  • python 中 re.match和re.search()函数
     两者都返回首次匹配字符串的索引,re.match函数只从头开始匹配,re.search函数不限制只从头开始匹配。001、re.match函数[root@PC1test2]#python3Python3.10.9(main,Mar12023,18:23:06)[GCC11.2.0]onlinuxType"help","copyright","credits"or"license"......
  • python 视频拆分成帧,帧合成视频
    参考python将视频切分成帧&&帧合成视频,下面的代码来自这篇博客。#====================视频拆分成帧===================================importcv2defvideo2frame(videos_path,frames_save_path,time_interval):''':paramvideos_path:视频的存放路径:par......
  • 果然python是直接可以使用requests去请求https站点的,意味着一般的扫描工具可以直接扫
    #coding:utf-8importrequests#请求地址#url="https://www.qlchat.com"url="https://www.baidu.com"headers={'user-agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chro......
  • python 从bulkblacklist信誉查询网站提交查询
    importurllibimporturllib2#importwebbrowserimportreimportsocketdefis_domain_in_black_list(domain,ip):try_time=3url="http://www.bulkblacklist.com/"foriinrange(try_time):try:data=......
  • python avro 数据格式使用demo
    {"name":"UEProcedures","type":"record","fields":[{"name":"imsi","type":"string"},{"name":"time_at","type":&quo......