搜索
首页后端开发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
如何使用numpy创建多维数组?如何使用numpy创建多维数组?Apr 29, 2025 am 12:27 AM

使用NumPy创建多维数组可以通过以下步骤实现:1)使用numpy.array()函数创建数组,例如np.array([[1,2,3],[4,5,6]])创建2D数组;2)使用np.zeros(),np.ones(),np.random.random()等函数创建特定值填充的数组;3)理解数组的shape和size属性,确保子数组长度一致,避免错误;4)使用np.reshape()函数改变数组形状;5)注意内存使用,确保代码清晰高效。

说明Numpy阵列中'广播”的概念。说明Numpy阵列中'广播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增强可读性,和Boostsperformance.Shere'shore'showitworks:1)较小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

举一个场景的示例,其中使用Python列表比使用数组更合适。举一个场景的示例,其中使用Python列表比使用数组更合适。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python数组中访问元素?您如何在Python数组中访问元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解吗?如果是,为什么以及如果不是为什么?Python中有可能理解吗?如果是,为什么以及如果不是为什么?Apr 28, 2025 pm 04:34 PM

文章讨论了由于语法歧义而导致的Python中元组理解的不可能。建议使用tuple()与发电机表达式使用tuple()有效地创建元组。(159个字符)

Python中的模块和包装是什么?Python中的模块和包装是什么?Apr 28, 2025 pm 04:33 PM

本文解释了Python中的模块和包装,它们的差异和用法。模块是单个文件,而软件包是带有__init__.py文件的目录,在层次上组织相关模块。

Python中的Docstring是什么?Python中的Docstring是什么?Apr 28, 2025 pm 04:30 PM

文章讨论了Python中的Docstrings,其用法和收益。主要问题:Docstrings对于代码文档和可访问性的重要性。

See all articles

热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

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

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能