如何使用Python解析SOAP WSDL接口返回的XML响应并提取字段?
Suds返回对象解析与数据存储解决方案
1. 基础字段提取方法
suds库返回的suds.sudsobject类型对象支持直接通过属性名访问对应字段,也可以通过官方提供的工具方法转为Python原生字典操作。
直接属性访问示例
# 获取COUNTRY数组属性 country_arr = cuntrylist.COUNTRY for country_item in country_arr: # 直接访问子对象的字段属性 country_code = country_item.COUNTRYCODE country_name = country_item.COUNTRYNAME print(f"国家代码:{country_code},国家名称:{country_name}")
转为原生字典操作(更适合复杂嵌套场景)
from suds.sudsobject import asdict # 递归将整个suds对象转为字典 country_resp_dict = asdict(cuntrylist) # 按普通字典逻辑取值 for country_item in country_resp_dict["COUNTRY"]: country_code = country_item["COUNTRYCODE"] country_name = country_item["COUNTRYNAME"]
2. 数据存入数据库实现
以下以SQLite为例,MySQL、PostgreSQL等数据库的操作逻辑一致,仅需替换对应的数据库连接驱动即可:
import sqlite3 from suds.sudsobject import asdict # 1. 解析响应数据 resp_dict = asdict(cuntrylist) data_list = [(item["COUNTRYCODE"], item["COUNTRYNAME"]) for item in resp_dict["COUNTRY"]] # 2. 数据库操作 conn = sqlite3.connect("local_data.db") cursor = conn.cursor() # 建表(仅首次执行需要) cursor.execute(""" CREATE TABLE IF NOT EXISTS country_list ( id INTEGER PRIMARY KEY AUTOINCREMENT, country_code VARCHAR(10) UNIQUE NOT NULL, country_name VARCHAR(100) NOT NULL ) """) # 批量插入数据,避免重复插入用INSERT OR IGNORE cursor.executemany(""" INSERT OR IGNORE INTO country_list (country_code, country_name) VALUES (?, ?) """, data_list) conn.commit() conn.close()
3. 复杂SOAP响应通用处理方案
针对多接口、复杂嵌套的suds返回结果,可按以下通用流程处理:
- 所有返回的suds对象统一先用
asdict()转为原生字典,嵌套结构会自动递归转换,无需处理特殊的suds类型 - 取值前可先打印转换后的字典结构,确认字段层级和命名,打印方法如下:
import json from suds.sudsobject import asdict resp_dict = asdict(your_suds_response) print(json.dumps(resp_dict, indent=2, ensure_ascii=False)) - 对于接口定义中的可选字段,取值时用字典的
get()方法避免KeyError,例如country_item.get("COUNTRYCODE", "") - 遇到列表类型的字段,先判断是否存在再遍历,避免空列表报错
内容的提问来源于stack exchange,提问作者Anees
相关产品推荐
相关产品推荐

