代码之家  ›  专栏  ›  技术社区  ›  max

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

  •  2
  • max  · 技术社区  · 6 年前

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

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

    tree.findall('.//title')
    tree.findall('.//p')
    

    但我如何同时评估它们呢?我在找一个类似 .// title or .//p

    我在一个特种部队的岗位上试过这个命令

    tree.findall('.//(p|title)')
    

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   alecxe    6 年前

    * self:: ( reference ):

    tree.xpath("//*[self::p or self::title]") 
    

    演示:

    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']
    
        2
  •  1
  •   kjhughes    6 年前

    尝试

    tree.findall('.//p | .//title')
    

    结果是两个节点集合并。