如何在lxml中获取元素的路径?

时间:2009-10-16 10:24:07

标签: python xpath lxml

我正在使用Python中的lxml中的XPath在HTML文档中搜索。我怎样才能获得某个元素的路径?以下是来自ruby nokogiri的例子:

page.xpath('//text()').each do |textnode|
    path = textnode.path
    puts path
end

打印例如' / html / body / div / div [1] / div [1] / p / text()[1] '这是我想要的字符串蟒。

4 个答案:

答案 0 :(得分:48)

使用ElementTree对象中的getpath

from lxml import etree

root = etree.fromstring('<foo><bar>Data</bar><bar><baz>data</baz>'
                        '<baz>data</baz></bar></foo>')

tree = etree.ElementTree(root)
for e in root.iter():
    print tree.getpath(e)

打印

/foo
/foo/bar[1]
/foo/bar[2]
/foo/bar[2]/baz[1]
/foo/bar[2]/baz[2]

答案 1 :(得分:18)

参见Xpath and XSLT with lxml from the lxml documentation这给出了包含文本

的元素的路径

一个例子是

import cStringIO
from lxml import etree

f = cStringIO.StringIO('<foo><bar><x1>hello</x1><x1>world</x1></bar></foo>')
tree = lxml.etree.parse(f)
find_text = etree.XPath("//text()")

# and print out the required data
print [tree.getpath( text.getparent()) for text in find_text(tree)]

# answer I get is 
>>> ['/foo/bar/x1[1]', '/foo/bar/x1[2]']

答案 2 :(得分:5)

如果您的代码段中只有元素,并且您想要元素的xpath,那么element.getroottree().getpath(element)将完成这项工作。

from lxml import etree

xml = '''
<test>
    <a/>
    <b>
       <i/>
       <ii/>
    </b>
</test>
'''
tree = etree.fromstring(xml)

for element in tree.iter():
    print element.getroottree().getpath(element)

答案 3 :(得分:4)

root = etree.parse(open('tmp.txt'))

for e in root.iter():
    print root.getpath(e)