使用 LXML 和 XPATH 解析后显示完整路径

Showing the full path after parsing with LXML and XPATH

有没有办法显示: (a) 定位节点的完整路径? (b) 显示路径节点的属性,即使我不知道这些属性可能叫什么?

例如,给定一个页面:

<!DOCTYPE html>
<HTML lang="en">
<HEAD>
  <META name="generator" content=
    "HTML Tidy for HTML5 for Linux version 5.2.0">
  <META charset="utf-8">
  <TITLE>blah ombid lipsum</TITLE>
</HEAD>
<BODY>
  <P>I'm the expected content</P>
  <DIV unexpectedattribute="very unexpected">
    <P>I'm wanted but not where you thought I'd be</P>
    <P class="strangeParagraphType">I'm also wanted text but also mislocated</P>
  </DIV>
</BODY>
</HTML>

我可以用

找到 想要的文字
# Import Python libraries
import sys
from lxml import html

page = open( 'findme.html' ).read()
tree  = html.fromstring(page)

wantedText = tree.xpath(
  '//*[contains(text(),"wanted text")]' )

print( len( wantedText ), ' item(s) of wanted text found')

然而,找到它后,我希望能够打印出所需文本位于以下位置的事实: /HTML/BODY/DIV/P ... 或者,更好的是,表明它位于 /HTML/BODY/DIV/P[2] ... 更好的是,表明它位于 /DIV 具有 unexpectedattribute="very unexpected" 且最终 <P> 具有 strangeParagraphType 的 class 的位置。

可以在您的第一个示例中使用类似这样的内容:

['/'.join(list([wt.tag] + [ancestor.tag for ancestor in wt.iterancestors()])[::-1]).upper() for wt in wantedText]

可以使用元素对象上的属性 属性 和一些自定义逻辑创建第三个:

wantedText[0].getparent().attrib
>>> {'unexpectedattribute': 'very unexpected'}
wantedText[0].attrib
>>> {'class': 'strangeParagraphType'}

编辑:重复答案 link 置顶绝对是更好的方法。