python lxml:无法通过标签+命名空间找到节点

python lxml: unable to find a node by tag+namespace

这是我的 XML:

x = """<?xml version="1.0" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <soap:Fault>
            <faultcode>soap:Client</faultcode>
            <faultstring>Fault occurred</faultstring>
            <faultactor>http://xxxxx/PrivateOfficeDataService.asmx</faultactor>
            <detail>
                <details xmlns="http://privateoffice.manzana.ru/">
                    <code>100261</code>
                    <description>access denied</description>
                </details>
            </detail>
        </soap:Fault>
    </soap:Body>
</soap:Envelope>"""

from lxml import etree

root = etree.fromstring(x)

现在,我想找到根的子节点。

这行不通:

print(root.find('Body'))
# None

这个有效:


print(root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body'))

# <Element {http://schemas.xmlsoap.org/soap/envelope/}Body at 0x10e6a1c40>

但是这样太麻烦了,所以我试试这个(也没用):

print(root.find('Body', namespaces={'soap': 'http://schemas.xmlsoap.org/soap/envelope/'}))
# None

我如何使用这个 namespaces arg 使其起作用?

您只需要使用 namespaces 参数中的前缀来引用前缀元素 soap:Body:

print(root.find('soap:Body', namespaces={'soap': 'http://schemas.xmlsoap.org/soap/envelope/'}))