首页 > 解决方案 > 获取 xml soap 响应而不是原始数据

问题描述

我正在尝试获取肥皂响应并阅读一些标签,然后将键和值放入字典中。

如果我可以使用直接生成的响应并对它执行 regd 操作,那就更好了。但由于我无法做到这一点,我尝试将响应存储在 xml 文件中,然后将其用于操作。

我的问题是生成的响应是原始形式。如何解决这个问题。

Example: <medical:totEeCnt val="2" />
          <medical:totMbrCnt val="2" />
          <medical:totDepCnt val="0" />


def soapTest():
    request = """<soapenv:Envelope.......
    auth = HTTPBasicAuth('', '')
        headers = {'content-type': 'application/soap+xml', 'SOAPAction': "", 'Host': 'bfx-b2b....com'}
        url = "https://bfx-b2b....com/B2BWEB/services/IProductPort"
        response = requests.post(url, data=request, headers=headers, auth=auth, verify=True)

        # Open local file
        fd = os.open('planRates.xml', os.O_RDWR|os.O_CREAT)

        # Convert response object into string
        response_str = str(response.content)

        # Write response to the file
        os.write(fd, response_str)

        # Close the file
        os.close(fd)

        tree = ET.parse('planRates.xml')
        root = tree.getroot()
        dict = {}

        print root
        for plan in root.findall('.//{http://services.b2b.../types/rates/dental}dentPln'):  # type: object

            plan_id = plan.get('cd')
            print plan

            print plan_id

            for rtGroup in plan.findall('.//{http://services.b2b....com/types/rates/dental}censRtGrp'):

                #print rtGroup
                for amt in rtGroup.findall('.//{http://services.b2b....com/types/rates/dental}totAnnPrem'):
                    # print amt
                    print amt.get('val')
                    amount =  amt.get('val')
                    dict[plan_id] = amount

                print dict

更新-:我做了几件事,我无法理解的是,使用它,进一步的操作正在工作,

     tree = ET.parse('data/planRates.xml')
        root = tree.getroot()
        dict = {}
        print tree
        print root
for plan in root.findall(..

输出 -

<xml.etree.ElementTree.ElementTree object at 0x100d7b910>
<Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope' at 0x101500450>

但是用了这个之后就不行了

    tree = ET.fromstring(response.text)
    print tree
for plan in tree.findall(..

输出-:

<Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope' at 0x10d624910>

基本上我只使用相同的对象。

标签: pythonrequestelementtree

解决方案


假设您得到一个想要作为正确 xml 对象的响应:

rt = resp.text.encode('utf-8')

# printed rt is something like:
'<soap:Envelope xmlns:soap="http://...">
 <soap:Envelope
 <AirShoppingRS xmlns="http://www.iata.org/IATA/EDIST" Version="16.1">
 <Document>...</soap:Envelope</soap:Envelope>'

# striping soapEnv
startTag = '<AirShoppingRS '
endTag = '</AirShoppingRS>'
trimmed = rt[rt.find(startTag): rt.find(endTag) + len(endTag)]

# parsing
from lxml import etree as et
root = et.fromstring(trimmed)

有了这个根元素,您可以使用 find 方法、xpath 或任何您喜欢的方法。
显然,您需要更改开始和结束标签以从响应中提取正确的元素,但您明白了,对吧?


推荐阅读