首页 后端开发 Python教程 在 Python 请求库中使用 XML

在 Python 请求库中使用 XML

Dec 30, 2024 am 08:31 AM

Working with XML in Python Requests library

什么是 XML? XML 是指可扩展标记语言,它需要存储结构化数据并对任何项目进行分组。在 XML 标记语言中,您可以创建具有任何名称的标签。最流行的 XML 示例 - 站点地图和 RSS 提要。

XML 文件示例:

<breakfast_menu>
   <food>
       <name>Belgian Waffles</name>
       <price>.95</price>
       <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
       <calories>650</calories> </food>
   <food>
       <name>Strawberry Belgian Waffles</name>
       <price>.95</price>
       <description>Light Belgian waffles covered with strawberries and whipped cream</description>
       <calories>900</calories> </food>
   <food>
       <name>Berry-Berry Belgian Waffles</name>
       <price>.95</price>
       <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
       <calories>900</calories> </food>
   <food>
       <name>French Toast</name>
       <price>.50</price>
       <description>Thick slices made from our homemade sourdough bread</description>
       <calories>600</calories> </food>
   <food>
       <name>Homestyle Breakfast</name>
       <price>.95</price>
       <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
       <calories>950</calories> </food>
</breakfast_menu>
登录后复制

在这个例子中,文件包含 breakfast_menu 全局标签,其中包含食物类别,每个食物类别包括名称、价格、描述和卡路里标签。

现在我们开始学习如何使用 XML 和 Python 请求库。首先我们需要准备好工作环境。

要创建新项目和虚拟环境,请安装 python3-virtualenv 包。它需要每个项目的分离要求。在 Debian/Ubuntu 中安装:

sudo apt install python3 python3-virtualenv -y
登录后复制

创建项目文件夹:

mkdir my_project
cd my_project
登录后复制

使用 env 命名的文件夹创建 Python 虚拟环境:

python3 -m venv env
登录后复制

激活虚拟环境:

source env/bin/activate
登录后复制

安装 PIP 的依赖项:

pip3 install requests
登录后复制

让我们开始编写代码吧。

创建 main.py 文件并在下面插入代码:

import requests
import xml.etree.ElementTree as ET
request = requests.get('https://www.w3schools.com/xml/simple.xml')
root = ET.fromstring(request.content)
for item in root.iter('*'):
    print(item.tag)
登录后复制

此代码片段帮助我们找到所有内部标签。

此代码的输出:

(env) user@localhost:~/my_project$ python3 main.py
breakfast_menu
food
name
price
description
calories
food
name
price
description
calories
food
name
price
description
calories
food
name
price
description
calories
food
name
price
description
calories
登录后复制

现在我们正在编写从内部元素获取值的代码。打开 main.py 文件并将之前的代码替换为:

import requests
import xml.etree.ElementTree as ET
request = requests.get('https://www.w3schools.com/xml/simple.xml')
root = ET.fromstring(request.content)
for item in root.iterfind('food'):
    print(item.findtext('name'))
    print(item.findtext('price'))
    print(item.findtext('description'))
    print(item.findtext('calories'))
登录后复制

我们收到了下一个结果:

(env) user@localhost:~/my_project$ python3 main.py
Belgian Waffles
.95
Two of our famous Belgian Waffles with plenty of real maple syrup
650
Strawberry Belgian Waffles
.95
Light Belgian waffles covered with strawberries and whipped cream
900
Berry-Berry Belgian Waffles
.95
Light Belgian waffles covered with an assortment of fresh berries and whipped cream
900
French Toast
.50
Thick slices made from our homemade sourdough bread
600
Homestyle Breakfast
.95
Two eggs, bacon or sausage, toast, and our ever-popular hash browns
950
登录后复制

最后一步,我们美化输出数据以使其更易于阅读:

import requests
import xml.etree.ElementTree as ET
request = requests.get('https://www.w3schools.com/xml/simple.xml')
root = ET.fromstring(request.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')))
登录后复制

此处输出:

(env) user@localhost:~/my_project$ python3 main.py
Name: Belgian Waffles. Price: .95. Description: Two of our famous Belgian Waffles with plenty of real maple syrup. Calories: 650
Name: Strawberry Belgian Waffles. Price: .95. Description: Light Belgian waffles covered with strawberries and whipped cream. Calories: 900
Name: Berry-Berry Belgian Waffles. Price: .95. Description: Light Belgian waffles covered with an assortment of fresh berries and whipped cream. Calories: 900
Name: French Toast. Price: .50. Description: Thick slices made from our homemade sourdough bread. Calories: 600
Name: Homestyle Breakfast. Price: .95. Description: Two eggs, bacon or sausage, toast, and our ever-popular hash browns. Calories: 950
登录后复制

来源材料:
XML 文件示例取自 W3Schools。


我的帖子有帮助吗?您可以在 Patreon 上支持我。

以上是在 Python 请求库中使用 XML的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何解决Linux终端中查看Python版本时遇到的权限问题? 如何解决Linux终端中查看Python版本时遇到的权限问题? Apr 01, 2025 pm 05:09 PM

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到? 如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到? Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

在Python中如何高效地将一个DataFrame的整列复制到另一个结构不同的DataFrame中? 在Python中如何高效地将一个DataFrame的整列复制到另一个结构不同的DataFrame中? Apr 01, 2025 pm 11:15 PM

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

Uvicorn是如何在没有serve_forever()的情况下持续监听HTTP请求的? Uvicorn是如何在没有serve_forever()的情况下持续监听HTTP请求的? Apr 01, 2025 pm 10:51 PM

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础? 如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础? Apr 02, 2025 am 07:18 AM

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

在Linux终端中使用python --version命令时如何解决权限问题? 在Linux终端中使用python --version命令时如何解决权限问题? Apr 02, 2025 am 06:36 AM

Linux终端中使用python...

如何绕过Investing.com的反爬虫机制获取新闻数据? 如何绕过Investing.com的反爬虫机制获取新闻数据? Apr 02, 2025 am 07:03 AM

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

See all articles