Python
Python 解析 HTTP SOAP 響應
我一直在關注HERE和HERE中的範例,嘗試解析 SOAP 響應,但無法獲得我想要的元素。
範例 SOAP 響應:
<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <loginResponse> <result> <metadataServerUrl>meta</metadataServerUrl> <passwordExpired>false</passwordExpired> <sandbox>true</sandbox> <serverUrl>someUrl</serverUrl> <sessionId>sessionId###</sessionId> <userId>userId###</userId> <userInfo></userId> </result> </loginResponse> </soapenv:Body> </soapenv:Envelope>
試圖取回
sessionId
但得到None
或空的列表。範常式式碼:
import xml.etree.ElementTree as ET ... r = requests.post(url, headers=header, data=payload) data = r.content ns = { "soapenv": "http://schemas.xmlsoap.org/soap/envelope/" } root = ET.fromstring(data) sid = root.findall(".//soapenv:sessionId", ns) # Tried these and any combination of those #sid = root.findall("./soapenv:Body/soapenv:loginResponse/soapenv:result/soapenv:sessionId", ns) #sid = root.findall("./soapenv:Body/loginResponse/result/sessionId", ns) #sid = root.findall("soapenv:sessionId", ns) print(sid)
有人能幫忙嗎?
您一直在嘗試尋找錯誤的 ns.
這是工作範例:
import xml.etree.ElementTree as ET data = """<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <loginResponse> <result> <metadataServerUrl>meta</metadataServerUrl> <passwordExpired>false</passwordExpired> <sandbox>true</sandbox> <serverUrl>someUrl</serverUrl> <sessionId>sessionId###</sessionId> <userId>userId###</userId> <userInfo></userInfo> </result> </loginResponse> </soapenv:Body> </soapenv:Envelope>""" root = ET.fromstring(data) sid = root.findall(".//{urn:partner.soap.sforce.com}sessionId") print(sid[0].text)