簡體   English   中英

使用 xpath 使用 lxml findall() 查找多種類型的標簽?

[英]Finding multiple types of tags with lxml findall() with xpath?

我想在一個 XML 文件中搜索多個標簽。

我可以分別評估這些命令:

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

但是我怎么能同時對它們進行評估。 我正在尋找像.// title or .//p這樣的語法

我從 SO 帖子中嘗試了此命令

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

但我收到了這個回溯錯誤SyntaxError: invalid descendant

與其遍歷樹兩次並加入節點集,不如執行一次查找*通配符標簽名稱並通過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']

嘗試

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

結果是兩個節點集的並集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM