python-3.xsoaprequestresponsetransport

How to parser soap response in python?


I found some similar solution but it's not working for me. I would like to know the best practice of parser the soap response.

My source code is :

from zeep.transports import Transport

response = transport.post_xml(address, payload, headers)
print(type(response))
print(response.content)

Output:

<class 'requests.models.Response'>


How can I get the **a key** value form the response? which simple and best library I should use. 
Thanks in advance.

Solution

  • Using the xml.etree.ElementTree in here

    It easily parse content and attribute.

    Demo Code

    import xml.etree.ElementTree as ET
    
    content = b'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>UNKNOW_LOCALID</faultstring><detail><ns2:SoapServiceFaultUtilisation xmlns:ns2="http://nps.ideosante.com/"><codeStatus>70</codeStatus><message>Unknown local ID: 1990967085562</message></ns2:SoapServiceFaultUtilisation></detail></soap:Fault></soap:Body></soap:Envelope>'
    print(content)
    
    root = ET.fromstring(content)
    print(root.find(".//codeStatus").text)
    

    Result

    b'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>UNKNOW_LOCALID</faultstring><detail><ns2:SoapServiceFaultUtilisation xmlns:ns2="http://nps.ideosante.com/"><codeStatus>70</codeStatus><message>Unknown local ID: 1990967085562</message></ns2:SoapServiceFaultUtilisation></detail></soap:Fault></soap:Body></soap:Envelope>' 
    70