gpt4 book ai didi

python - 使用 xml 在 Python 中解析 xml(一种正确的方法)

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:14 25 4
gpt4 key购买 nike

我使用 Python 中的 requests 模块获取响应,响应采用 xml 形式。我想解析它并从每个“dt”标签中获取详细信息。我无法使用 lxml 做到这一点。

这是 xml 响应:

<?xml version="1.0" encoding="utf-8" ?>
<entry_list version="1.0">
<entry id="harsh">
<ew>harsh</ew><subj>MD-2</subj><hw>harsh</hw>
<sound><wav>harsh001.wav</wav><wpr>!h@rsh</wpr></sound>
<pr>ˈhärsh</pr>
<fl>adjective</fl>
<et>Middle English <it>harsk,</it> of Scandinavian origin; akin to Norwegian <it>harsk</it> harsh</et>
<def>
<date>14th century</date>
<sn>1</sn>
<dt>:having a coarse uneven surface that is rough or unpleasant to the touch</dt>
<sn>2 a</sn>
<dt>:causing a disagreeable or painful sensory reaction :<sx>irritating</sx></dt>
<sn>b</sn>
<dt>:physically discomforting :<sx>painful</sx></dt>
<sn>3</sn>
<dt>:unduly exacting :<sx>severe</sx></dt>
<sn>4</sn>
<dt>:lacking in aesthetic appeal or refinement :<sx>crude</sx></dt>
<ss>rough</ss>
</def>
<uro><ure>harsh*ly</ure> <fl>adverb</fl></uro>
<uro><ure>harsh*ness</ure> <fl>noun</fl></uro>
</entry>
</entry_list>

最佳答案

一种简单的方法是遍历 xml 文档的层次结构。

import requests
from lxml import etree

re = requests.get(url)
root = etree.fromstring(re.content)
print(root.xpath('//entry_list/entry/def/dt/text()'))

这将为 xml 文档中的每个“dt”标记提供文本值。

关于python - 使用 xml 在 Python 中解析 xml(一种正确的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com