XPath到Python中的命名空间XML?

MrC*_*tro 3 python xpath lxml epub3

我正在使用带xpath的lxml来解析epub3,xhtml内容文件.

我想选择li具有该属性的所有节点,epub:type="footnote" 例如

<li epub:type="footnote" id="fn14"> ... </li>
Run Code Online (Sandbox Code Playgroud)

我找不到合适的xpath表达式.

表达方式

//*[self::li][@id]
Run Code Online (Sandbox Code Playgroud)

选择li具有属性id的所有节点,但是当我尝试时

//*[self::li][@epub:type]
Run Code Online (Sandbox Code Playgroud)

我收到了错误

lxml.etree.XPathEvalError: Undefined namespace prefix
Run Code Online (Sandbox Code Playgroud)

XML是

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="stylesheet.css" />
    </head>
    <body> 
        <section class="footnotes">
            <hr />
            <ol>
                <li id="fn1" epub:type="footnote">
                    <p>See foo</p>
                </li>
            </ol>
        </section>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

关于如何编写正确表达式的任何建议?

kjh*_*hes 5

您是否epub已将名称空间前缀声明为lxml?

>>> tree.getroot().xpath(
...     "//li[@epub:type = 'footnote']", 
...     namespaces={'epub':'http://www.idpf.org/2007/ops'}
...     )
Run Code Online (Sandbox Code Playgroud)

每个问题更新更新

XHTML命名空间也让你沮丧.尝试:

>>> tree.getroot().xpath(
...     "//xhtml:li[@epub:type = 'footnote']", 
...     namespaces={'epub':'http://www.idpf.org/2007/ops', 'xhtml': 'http://www.w3.org/1999/xhtml'}
...     )
Run Code Online (Sandbox Code Playgroud)