在 Python 请求库中使用 XML

在 python 请求库中使用 xml

本文介绍如何使用Python的requests库和xml.etree.ElementTree模块解析XML数据。XML(可扩展标记语言)用于存储结构化数据。 常见的XML应用包括站点地图和RSS订阅。

以下是一个XML文件示例:

      belgian waffles    $5.95    two of our famous belgian waffles with plenty of real maple syrup    650        strawberry belgian waffles    $7.95    light belgian waffles covered with strawberries and whipped cream    900        berry-berry belgian waffles    $8.95    light belgian waffles covered with an assortment of fresh berries and whipped cream    900        french toast    $4.50    thick slices made from our homemade sourdough bread    600        homestyle breakfast    $6.95    two eggs, bacon or sausage, toast, and our ever-popular hash browns    950  

登录后复制

这个例子展示了一个breakfast_menu根元素,包含多个food元素,每个food元素包含name、price、description和calories子元素。

接下来,我们将学习如何用Python解析此类XML数据。首先,设置开发环境:

立即学习“Python免费学习笔记(深入)”;

安装必要的库:

sudo apt install python3 python3-virtualenv -y  # Debian/Ubuntupython3 -m venv env  # 创建虚拟环境source env/bin/activate  # 激活虚拟环境pip3 install requests

登录后复制

创建main.py文件并输入以下代码:

步骤一:获取所有标签名

import requestsimport xml.etree.ElementTree as ETresponse = requests.get('https://www.w3schools.com/xml/simple.xml')root = ET.fromstring(response.content)for item in root.iter('*'):    print(item.tag)

登录后复制

这将打印出所有XML标签的名称。

步骤二:提取特定元素的值

import requestsimport xml.etree.ElementTree as ETresponse = requests.get('https://www.w3schools.com/xml/simple.xml')root = ET.fromstring(response.content)for item in root.iterfind('food'):    print(item.findtext('name'))    print(item.findtext('price'))    print(item.findtext('description'))    print(item.findtext('calories'))

登录后复制

这将打印每个食物的名称、价格、描述和卡路里信息。

步骤三:格式化输出

为了更清晰地显示结果,我们可以格式化输出:

import requestsimport xml.etree.ElementTree as ETresponse = requests.get('https://www.w3schools.com/xml/simple.xml')root = ET.fromstring(response.content)for item in root.iterfind('food'):    print('Name: {}, Price: {}, Description: {}, Calories: {}'.format(        item.findtext('name'), item.findtext('price'), item.findtext('description'), item.findtext('calories')))

登录后复制

这将以更易读的格式打印输出。

XML文件示例来自w3schools。

希望本文对您有所帮助! 您可以通过你的赞助链接来支持我的工作。

以上就是在 Python 请求库中使用 XML的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2174662.html

(0)
上一篇 2025年2月25日 12:21:36
下一篇 2025年2月24日 04:23:20

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论