使用 lxml findall() 和 xpath 查找多种类型的标签?

max*_*max 7 python xml lxml

我想在 XML 文件中搜索多个标签。

我可以单独评估这些命令:

tree.findall('.//title')
tree.findall('.//p')
Run Code Online (Sandbox Code Playgroud)

但我怎样才能同时评估它们呢?我正在寻找类似的语法.// title or .//p

我在 SO 帖子中尝试了这个命令

tree.findall('.//(p|title)')
Run Code Online (Sandbox Code Playgroud)

但我收到这个回溯错误SyntaxError: invalid descendant

ale*_*cxe 5

与其遍历树两次并加入节点集,不如一次性查找*通配符标签名称并通过self::参考)检查标签名称:

tree.xpath("//*[self::p or self::title]") 
Run Code Online (Sandbox Code Playgroud)

演示:

In [1]: from lxml.html import fromstring

In [2]: html = """
    ...: <body>
    ...:     <p>Paragraph 1</p>
    ...:     <div>Other info</div>
    ...:     <title>Title 1</title>
    ...:     <span>
    ...:         <p>Paragraph 2</p>
    ...:     </span>
    ...:     <title>Title 2</title>
    ...: </body>
    ...: """

In [3]: root = fromstring(html)

In [4]: [elm.text_content() for elm in root.xpath("//*[self::p or self::title]")] 
Out[4]: ['Paragraph 1', 'Title 1', 'Paragraph 2', 'Title 2']
Run Code Online (Sandbox Code Playgroud)