我一直在关注这里和这里尝试解析 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)
有人能帮忙吗?
答案1
您尝试搜索错误的 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)