gpt4 book ai didi

python - 如何用python解析xml响应?

转载 作者:行者123 更新时间:2023-12-01 08:07:37 26 4
gpt4 key购买 nike

我从 API 调用中获取 XML 响应(使用 python)。我如何解析 xml 响应?

XML 响应:

200 OK
<?xml version='1.0' encoding='UTF-8' ?>
<mail>
<delivery id='123'>
<deliver_id>xxx</deliver_id>
<request_id>xxx</request_id>
<exec_cnt>1</exec_cnt>
<result code='0'>success</result>
</delivery>
</mail>

这是请求中获取响应的主要代码:

def sendMail():
context = ssl._create_unverified_context()
header = {"Content-Type": "text/xml"}
url = "xxx"
body = "xxx"
try:
conn = http.client.HTTPSConnection("54.199.162.74", context=context)
conn.request(method="POST", url=url, body=body.encode("UTF-8"), headers=header, encode_chunked=True)
response = conn.getresponse()
mail_response = response.read()
print(response.status, response.reason)
print(mail_response.decode('utf-8'))
except Exception as e:
print(e)
return response

sendMail()

我尝试使用此代码解析 xml 响应,但始终返回错误

import xml.etree.ElementTree as ET
response_xml_as_string = mail_response.decode('utf-8')

>>> tree = ET.fromstring(response_xml_as_string)
>>> root = tree.getroot()
>>> root.tag
'mail'
>>> root.attrib
{}
>>> for child in root:
... print(child.tag, child.attrib)

我得到的错误:

'xml.etree.ElementTree.Element' object has no attribute 'getroot'

最佳答案

您还可以使用BeatuifulSoup来解析和提取内容

from bs4 import BeautifulSoup as Soup
resp = """<?xml version='1.0' encoding='UTF-8' ?>
<mail>
<delivery id='123'>
<deliver_id>xxx</deliver_id>
<request_id>yyy</request_id>
<exec_cnt>1</exec_cnt>
<result code='0'>success</result>
</delivery>
</mail>"""

soup = Soup(resp,'xml')
#extracting data between request_id Tag
print(soup.request_id.get_text())

#extracting data between deliver ID Tag
print(soup.deliver_id.get_text())

#extracting the result code and the data between the tag
print(soup.result['code'])
print(soup.result.get_text())

您可以在下面的链接中找到有关美丽汤的更多信息

https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html

关于python - 如何用python解析xml响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55466143/

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