社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

[精华] Python解析XML的利器

爱情的枪 • 10 年前 • 5477 次点击  

最近在做爬虫遇到要解析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
 
5477 次点击  
文章 [ 3 ]  |  最新文章 10 年前
我心荡漾
Reply   •   1 楼
我心荡漾    10 年前

python 采集哪家强? 当属 Scrapy 啦

Leo
Reply   •   2 楼
Leo    10 年前

棒狄斯奈

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

支持~