Py学习  »  Python

[精华] Python解析XML的利器

爱情的枪 • 9 年前 • 4728 次点击  

最近在做爬虫遇到要解析XML数据的问题

研究了一下,推荐大家使用 ElementTree 来解析,感觉 还不错哈,

例如,你想要解析:

<?xml version="1.0"?>
<doc>
    <branch name="testing" hash="1cdf045c">
        text,source
    </branch>
    <branch name="release01" hash="f200013e">
        <sub-branch name="subrelease01">
            xml,sgml
        </sub-branch>
    </branch>
    <branch name="invalid">
    </branch>
</doc>

找出branch这个结点的属性数据的方法是:

import xml.etree.cElementTree as ET
tree = ET.ElementTree(file='doc1.xml')
for elem in tree.iter(tag='branch'):
    print elem.tag, elem.attrib

打印出:

branch {'hash': '1cdf045c', 'name': 'testing'}
branch {'hash': 'f200013e', 'name': 'release01'}
branch {'name': 'invalid'}

参考:

  1. http://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/processing-xml-in-python-with-element-tree.html
  2. https://docs.python.org/2/library/xml.etree.elementtree.html
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/552
 
4728 次点击  
文章 [ 3 ]  |  最新文章 9 年前
我心荡漾
Reply   •   1 楼
我心荡漾    9 年前

python 采集哪家强? 当属 Scrapy 啦

Leo
Reply   •   2 楼
Leo    9 年前

棒狄斯奈

Py站长
Reply   •   3 楼
Py站长    9 年前

支持~