Python實(shí)現(xiàn)提取XML內(nèi)容并保存到Excel中的方法-創(chuàng)新互聯(lián)

本文實(shí)例講述了Python實(shí)現(xiàn)提取XML內(nèi)容并保存到Excel中的方法。分享給大家供大家參考,具體如下:

和田網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián)公司,和田網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為和田成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢(qián),請(qǐng)找那個(gè)售后服務(wù)好的和田做網(wǎng)站的公司定做!

最近做一個(gè)項(xiàng)目是解析XML文件,提取其中的chatid和lt、timestamp等信息,存到excel里。

1.解析xml,提取數(shù)據(jù)

使用python自帶的xml.dom中的minidom(也可以用lxml)

xml文件如下:

Python實(shí)現(xiàn)提取XML內(nèi)容并保存到Excel中的方法

minidom.parse()#解析文件,返回DOM對(duì)象
_get_documentElement()DOM是樹(shù)形結(jié)構(gòu),獲得了樹(shù)形結(jié)構(gòu)的根節(jié)點(diǎn)
getElementsByTagName()根據(jù)name查找根目錄下的子節(jié)點(diǎn)
getAttribute()獲取DOM節(jié)點(diǎn)的屬性的值

提取的代碼如下:

class get_xml():
  #加載獲取xml的文檔對(duì)象
  def __init__(self,address):
    #解析address文件,返回DOM對(duì)象,address為文件地址
    self.doc = minidom.parse(address)
    #DOM是樹(shù)形結(jié)構(gòu),_get_documentElement()獲得了樹(shù)形結(jié)構(gòu)的根節(jié)點(diǎn)
    self.root = self.doc._get_documentElement()
    #.getElementsByTagName(),根據(jù)name查找根目錄下的子節(jié)點(diǎn)
    self.httpSample_nodes = self.root.getElementsByTagName('httpSample')
  def getxmldata(self):
    data_list=[]
    j = -1
    responseData_node = self.root.getElementsByTagName("responseData")
    for i in self.httpSample_nodes:
      j = j+1
      #getAttribute(),獲取DOM節(jié)點(diǎn)的屬性的值
      if i.getAttribute("lb") == "發(fā)送信息":
        a = 'chatId":"(.*?)"'
      elif i.getAttribute("lb") == "接收信息":
        # a = "chatId%3A%22(.*?)%22"
        a = "info%3A%22(.*?)%22"
      if (i.getAttribute("lb") == "發(fā)送信息" or i.getAttribute("lb") == "接收信息") and i.getAttribute("rc") == "200":
        try:
          #使用re包里面的方法,通過(guò)正則表達(dá)式提取數(shù)據(jù)
          b = re.search(a, responseData_node[j].firstChild.data)
          if b is not None:
            d = b.group(1)
            print("d:",d)
            data_list.append((d, i.getAttribute("ts"), i.getAttribute("lt"),i.getAttribute("lb")))
        except:
          pass
    return data_list

網(wǎng)站標(biāo)題:Python實(shí)現(xiàn)提取XML內(nèi)容并保存到Excel中的方法-創(chuàng)新互聯(lián)
標(biāo)題網(wǎng)址:http://muchs.cn/article36/dsidsg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)、品牌網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化品牌網(wǎng)站制作、外貿(mào)建站虛擬主機(jī)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

營(yíng)銷(xiāo)型網(wǎng)站建設(shè)