Python 调用 Webservice 并解析 Xml

客户端

Python 中的 Webservice 客户端 suds 常用的有两个包

suds-py3

suds

目前选择的是 suds,安装

1
pip install suds

解析

具体实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import xml.etree.ElementTree as ET

from suds.client import Client

url = "http://172.19.7.7/PSIGW/PeopleSoftServiceListeningConnector/PSFT_HR/CST_INF_SERVICE.13.wsdl"
client = Client(url)

print(client)

result = client.service.CST_INF_JOBCODE_OUT(
BATCH_NUM="xxx",
IFAC_CODE="xxx",
REQUEST_DATA="<![CDATA[<ROOT><CST_PAGENUMBER>1</CST_PAGENUMBER><CST_PAGESIZE>300</CST_PAGESIZE><RUN_TYPE>ALL</RUN_TYPE><TOKENID>xxx</TOKENID><SYSTEM>xxx</SYSTEM></ROOT>]]>",
)

root = ET.fromstring(result["RETURN_DATA"])
for child in root:
print(child[2].text)

先看看看 client 中的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
Suds ( https://fedorahosted.org/suds/ )  version: 1.0.0

Service ( CST_INF_SERVICE ) tns="http://xmlns.oracle.com/Enterprise/Tools/services/CST_INF_SERVICE.13"
Prefixes (2)
ns0 = "http://xmlns.oracle.com/Enterprise/Tools/schemas/CST_INF_REQ.V1"
ns1 = "http://xmlns.oracle.com/Enterprise/Tools/schemas/CST_INF_RSP.V1"
Ports (1):
(CST_INF_SERVICE_Port)
Methods (1):
CST_INF_JOBCODE_OUT(xs:string BATCH_NUM, xs:string IFAC_CODE, xs:string REQUEST_DATA)
Types (2):
ns0:REQUEST
ns1:RESPONSE

如上所示 CST_INF_JOBCODE_OUT 方法有 3 个参数而且都是 string 类型,这里重点说说 REQUEST_DATA,原生请求 Xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:erp="http://xmlns.oracle.com/Enterprise/Tools/schemas/CST_INF_R
EQ.V1">
<soapenv:Header/>
<soapenv:Body>
<erp:REQUEST>
<erp:BATCH_NUM>xxx</erp:BATCH_NUM>
<erp:IFAC_CODE>xxx</erp:IFAC_CODE>
<erp:REQUEST_DATA>
<![CDATA[
<ROOT>
<CST_PAGENUMBER>100</CST_PAGENUMBER>
<CST_PAGESIZE>1</CST_PAGESIZE>
<RUN_TYPE>ALL</RUN_TYPE>
<TOKENID>xxx</TOKENID>
<SYSTEM>xxx</SYSTEM>
</ROOT>]]>
</erp:REQUEST_DATA>
</erp:REQUEST>
</soapenv:Body>
</soapenv:Envelope>

对于 REQUEST_DATA 中的 CDATA 包裹部分应该选择原样传入

1
2
3
4
5
6
7
8
<![CDATA[
<ROOT>
<CST_PAGENUMBER>100</CST_PAGENUMBER>
<CST_PAGESIZE>1</CST_PAGESIZE>
<RUN_TYPE>ALL</RUN_TYPE>
<TOKENID>xxx</TOKENID>
<SYSTEM>xxx</SYSTEM>
</ROOT>]]>

最后是对 xml 的解析可以利用 ElementTree,具体可以参考

ElementTree