获取xml soap响应而不是原始数据

时间:2018-08-28 10:48:15

标签: python request elementtree

我试图获得肥皂反应并读取一些标签,然后将键和值放入字典中。

更好的情况是,我可以使用直接生成的响应并对它执行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>

基本上我只使用同一对象。

1 个答案:

答案 0 :(得分:0)

假设您收到想要作为适当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或您喜欢的任何东西。
显然,您需要更改开始和结束标签以从响应中提取正确的元素,但是您知道了,对吧?