zoukankan      html  css  js  c++  java
  • python使用ElementTree解析XML文件

    一、将XML网页保存到本地


    要加载XML文件首先应该将网页上的信息提取出来,保存为本地XML文件。抓取网页信息可以python的urllib模块。

    代码如下:

    from urllib import urlopen
    url = "http://********/**"
    resp = urlopen(url).read()
    f = open('文件保存路径', 'w')
    f.write(resp)
    f.close()

    二、解析XML文件

    python有许多可以用来解析XML文件的函数,在这里介绍ElementTree(简称ET).它提供轻量级的python式API。实现逻辑简单,解析效率高。利用ET解析XML文件的方法是:先找出父级标签,然后再一级一级循环找出所需要的子标签,代码如下:

    import xml.etree.cElementTree as ET
    tree = ET.parse("***.xml")  #加载xml文件
    root = tree.getroot()  #得到第二级标签
    for child_of_root in root[1]:#root[1]为第二级标签中的第二个子标签 
        for child1 in child_of_root[7]: #原理同上
            for child2 in child1:
                print child2.tag, child2.attrib, child2.text
        for child3 in child_of_root[8]:
            for child4 in child3:
                print child4.tag, child4.attrib, child4.text

    在上述代码中,child_of_root[7]表示在该级标签中的第八个子标签,在for child2 in child1中是遍历child1的所有子标签,打印出子标签的名称、属性、文本。这样就可以将XML文件解析完成,得到我们所想要的信息。

  • 相关阅读:
    inline-block 文字与图片不对齐
    js去除数组重复项
    react2
    kfaka windows安装
    sigar 监控服务器硬件信息
    Disruptor
    Servlet 3特性:异步Servlet
    jvmtop 监控
    eclipse如何debug调试jdk源码
    一致性hash算法
  • 原文地址:https://www.cnblogs.com/l5623064/p/8574624.html
Copyright © 2011-2022 走看看