我正在構建一個站點(flask)并使用支付 api 但這是我第一次使用 api,我不知道如何從 xml 獲取變數
這是從請求回傳的xml
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="API_Library">
<SOAP-ENV:Body>
<ns1:gerarReferenciaMBResponse>
<sucesso>true</sucesso>
<entidade>82142</entidade>
<referencia>000762738</referencia>
<valor>5</valor>
<estado>0</estado>
<resposta>OK</resposta>
</ns1:gerarReferenciaMBResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
我的請求看起來像這樣
import requests
url = "https://sandbox.***.pt/****/api/api.php?wsdl=replica.*****.wsdl"
payload = "<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="API_Library">
<soapenv:Header/>
<soapenv:Body>
<api:gerarReferenciaMB>
<valor>5</valor>
<chave>****</chave>
<id>1</id>
<!--Optional:-->
<admin_callback>0</admin_callback>
<!--Optional:-->
<token>0</token>
<!--Zero or more repetitions:-->
<campos_extra>
<id>0</id>
<valor>0</valor>
</campos_extra>
<!--Optional:-->
<per_dup>0</per_dup>
<!--Optional:-->
<testa_pagamento>1</testa_pagamento>
</api:gerarReferenciaMB>
</soapenv:Body>
</soapenv:Envelope>"
headers = {
'Content-Type': 'text/xml'
}
response = requests.request("POST", url, headers=headers, data=payload)
我的問題是假設我如何獲取“和”值來設定變數。
uj5u.com熱心網友回復:
我剛剛找到了如何獲得它:
for item in a.split("</entidade>"):
if "<entidade>" in item:
print(item[item.find("<entidade>") len("<entidade>"):])
for item in a.split("</referencia>"):
if "<referencia>" in item:
print(item[item.find("<referencia>") len("<referencia>"):])
這將列印標簽之間的內容
uj5u.com熱心網友回復:
嘗試以下操作 - 它將創建一個包含您正在查找的資料的 python 字典
import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="API_Library">
<SOAP-ENV:Body>
<ns1:gerarReferenciaMBResponse>
<sucesso>true</sucesso>
<entidade>82142</entidade>
<referencia>000762738</referencia>
<valor>5</valor>
<estado>0</estado>
<resposta>OK</resposta>
</ns1:gerarReferenciaMBResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
root = ET.fromstring(xml)
elements = ['entidade','referencia']
data = {ele.tag: ele.text for ele in list(list(root)[0][0]) if ele.tag in elements}
print(data)
輸出
{'entidade': '82142', 'referencia': '000762738'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/331651.html
下一篇:如何在XSD中定義全域
