如何在Python中从Requests lib返回的Pretty Print

时间:2016-06-17 20:29:46

标签: xml web-services soap python-requests pretty-print

我正在使用"请求"用于运行SOAP服务的库。

headers = {'content-type': 'application/json'}
response = requests.post(test_url,data=testData.request_body,headers=headers)

响应如下(未格式化)

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://xxx.abc.in"><SOAP-ENV:Body><ns1:LoginResponse><return><SessionID>abc12345</SessionID><ResponseCode>0</ResponseCode><ResponseMessage>Successful</ResponseMessage></return></ns1:LoginResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

我怎么打印这个?

2 个答案:

答案 0 :(得分:0)

你可以使用beautifulsoup传递"xml"作为解析器:

x = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://xxx.abc.in"><SOAP-ENV:Body><ns1:LoginResponse><return><SessionID>abc12345</SessionID><ResponseCode>0</ResponseCode><ResponseMessage>Successful</ResponseMessage></return></ns1:LoginResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>'''

print(BeautifulSoup(x, "xml").prettify())

输出:

<?xml version="1.0" encoding="utf-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://xxx.abc.in">
 <SOAP-ENV:Body>
  <ns1:LoginResponse>
   <return>
    <SessionID>
     abc12345
    </SessionID>
    <ResponseCode>
     0
    </ResponseCode>
    <ResponseMessage>
     Successful
    </ResponseMessage>
   </return>
  </ns1:LoginResponse>
 </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

答案 1 :(得分:0)

假设你是从xml字符串开始的:

#LXML
from lxml import etree
xmlRootNode = etree.fromstring(resp_str)
xmlstr = etree.tostring(xmlRootNode, xml_declaration=True, encoding="UTF-8", pretty_print=True)

#xml
import xml.etree.ElementTree as ET
import xml.dom.minidom
s = ET.tostring(xmlRootNode, encoding="UTF-8", method="xml")
xmln = xml.dom.minidom.parseString(resp_str)
xmlstr = xmln.toprettyxml()