[英]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.