写在前面
工作中偶尔需要对接webservice的接口;网上搜了一下,不少的教程推荐使用suds。
但是suds这个包早就停止维护了。对于简单的调用,我还是觉得自己写更方便点,够用就行。
webservice 介绍
想了解的我建议还是看下百度百科,这里就不重复那些内容了。
webservice SOAP,通常使用xml格式。
获取到webservice的接口地址后,直接在浏览器中打开,会看到数据交互样例。
直接使用Python发送请求就行,剩下的就是解析xml了。
发送请求
这里直接使用requests
需要注意的是,需要在webservice样例中拿到headers和body
示例接口地址:http://192.168.1.10/Test_web/Test_web.asmx
# 接口不同,消息体和需要传入的参数也是不同的。body可以参照你需要请求的webservice接口的数据样例
body = '''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Test_Info_Frmweb xmlns="http://localhost/">
<sImport>''' + str(这里添加上需要发送的参数,这里可以指定编码) + '''</sImport>
</Test_Info_Frmweb>
</soap:Body>
</soap:Envelope>'''
# 需要注意的是这里的SOAPAction,一定要正确。
headers = {
'Host': '192.168.1.10',
'Content-Type': 'text/xml; charset=utf-8',
'Content-Length': str(len(body)),
'SOAPAction': "http://localhost/Test_Info_Frmweb"
}
# 发送请求
res_xml = requests.post(url=webservice_url, data=body.encode('utf-8'), headers=headers).content.decode('utf-8')
解析xml
# 这里使用内置的 xml 库;parse是解析xml文件的,parseString是解析数据流的
from xml.dom.minidom import parse, parseString
# print(res_xml)
dom_tree = parseString(res_xml)
dom_obj = dom_tree.documentElement
# print(dom_obj)
# 这里可以根据标签名称进行搜索,有多个相同标签的话,可以使用for循环提取
this_dom_res_obj = dom_obj.getElementsByTagName('Test_Info_Frmweb_Result')
# 提取消息体
this_dom_data = this_dom_res_obj[0].childNodes[0].data
print(this_dom_data)