11

目标: 获取<Name>标签内的值并打印出来。下面是简化的 XML。

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <GetStartEndPointResponse xmlns="http://www.etis.fskab.se/v1.0/ETISws">
         <GetStartEndPointResult>
            <Code>0</Code>
            <Message />
            <StartPoints>
               <Point>
                  <Id>545</Id>
                  <Name>Get Me</Name>
                  <Type>sometype</Type>
                  <X>333</X>
                  <Y>222</Y>
               </Point>
               <Point>
                  <Id>634</Id>
                  <Name>Get me too</Name>
                  <Type>sometype</Type>
                  <X>555</X>
                  <Y>777</Y>
               </Point>
            </StartPoints>
         </GetStartEndPointResult>
      </GetStartEndPointResponse>
   </soap:Body>
</soap:Envelope>

试图:

import requests
from xml.etree import ElementTree

response = requests.get('http://www.labs.skanetrafiken.se/v2.2/querystation.asp?inpPointfr=yst')

# XML parsing here
dom = ElementTree.fromstring(response.text)
names = dom.findall('*/Name')
for name in names:
    print(name.text)

我读过其他人建议zeep解析soap xml,但我发现很难理解。

4

3 回答 3

23

这里的问题是处理 XML 命名空间:

import requests
from xml.etree import ElementTree

response = requests.get('http://www.labs.skanetrafiken.se/v2.2/querystation.asp?inpPointfr=yst')

# define namespace mappings to use as shorthand below
namespaces = {
    'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
    'a': 'http://www.etis.fskab.se/v1.0/ETISws',
}
dom = ElementTree.fromstring(response.content)

# reference the namespace mappings here by `<name>:`
names = dom.findall(
    './soap:Body'
    '/a:GetStartEndPointResponse'
    '/a:GetStartEndPointResult'
    '/a:StartPoints'
    '/a:Point'
    '/a:Name',
    namespaces,
)
for name in names:
    print(name.text)

命名空间分别来自和节点上的xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"xmlns="http://www.etis.fskab.se/v1.0/ETISws"属性。EnvelopeGetStartEndPointResponse

请记住,命名空间被父节点的所有子节点继承,即使命名空间没有在子标签上明确指定为<namespace:tag>.

注意:我必须使用response.content而不是response.body.

于 2017-07-22T05:05:01.963 回答
9

一个老问题,但值得一提的是此任务的另一个选项。

我喜欢使用xmltodict (Github)一个轻量级的XMLPython 字典转换器。

将您的肥皂响应放入一个名为的变量中stack

解析它xmltodict.parse

In [48]: stack_d = xmltodict.parse(stack)

检查结果:

In [49]: stack_d
Out[49]:
OrderedDict([('soap:Envelope',
            OrderedDict([('@xmlns:soap',
                            'http://schemas.xmlsoap.org/soap/envelope/'),
                        ('@xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'),
                        ('@xmlns:xsi',
                            'http://www.w3.org/2001/XMLSchema-instance'),
                        ('soap:Body',
                            OrderedDict([('GetStartEndPointResponse',
                                        OrderedDict([('@xmlns',
                                                        'http://www.etis.fskab.se/v1.0/ETISws'),
                                                    ('GetStartEndPointResult',
                                                        OrderedDict([('Code',
                                                                    '0'),
                                                                    ('Message',
                                                                    None),
                                                                    ('StartPoints',
                                                                    OrderedDict([('Point',
                                                                                    [OrderedDict([('Id',
                                                                                                '545'),
                                                                                                ('Name',
                                                                                                'Get Me'),
                                                                                                ('Type',
                                                                                                'sometype'),
                                                                                                ('X',
                                                                                                '333'),
                                                                                                ('Y',
                                                                                                '222')]),
                                                                                    OrderedDict([('Id',
                                                                                                '634'),
                                                                                                ('Name',
                                                                                                'Get me too'),
                                                                                                ('Type',
                                                                                                'sometype'),
                                                                                                ('X',
                                                                                                '555'),
                                                                                                ('Y',
                                                                                                '777')])])]))]))]))]))]))])

此时,它变得像浏览 python 字典一样简单

In [50]: stack_d['soap:Envelope']['soap:Body']['GetStartEndPointResponse']['GetStartEndPointResult']['StartPoints']['Point']
Out[50]:
[OrderedDict([('Id', '545'),
            ('Name', 'Get Me'),
            ('Type', 'sometype'),
            ('X', '333'),
            ('Y', '222')]),
OrderedDict([('Id', '634'),
            ('Name', 'Get me too'),
            ('Type', 'sometype'),
            ('X', '555'),
            ('Y', '777')])]
于 2019-02-01T06:18:00.210 回答
2

再次回答一个老问题,但我认为这个解决方案值得分享。使用 BeautifulSoup 对我来说是小菜一碟。您可以在此处安装 BeautifulSoup 表单。

from bs4 import BeautifulSoup
xml = BeautifulSoup(xml_string, 'xml')
xml.find('soap:Body') # to get the soup:Body tag. 
xml.find('X') # for X tag
于 2021-02-07T09:07:13.650 回答