如何找到文本的父节点?

How to find text's Parent Node?

如果我使用:

import requests
from lxml import html

response = request.get(url='someurl')
tree = html.document_fromstring(response.text)


all_text = tree.xpath('//text()')     # which give all text from page

在这个 all_text 列表中,我们有页面中的所有文本。现在我想知道是否:

text_searched = all_text[all_text.index('any string which is in all_text list')]

是否可以获取到被搜索文本的web元素?

您可以使用getparent()方法来达到这个目的,例如:

.....
.....
all_text = tree.xpath('//text()')

first_text = all_text[0]
parent_element = first_text.getparent()

print html.tostring(parent_element)

请注意,如果当前文本元素位于同一父元素中的元素节点之后,则 getparent() might not be the one you expected 的行为。由于 lxml 实现的树模型,在这种情况下,文本被视为前一个元素的 tail 而不是包含元素的 child,因此 getparent() 将 return 前面的元素。请参阅下面的示例以清楚地了解我一直在谈论的内容:

from lxml import html
raw = '''<div>
    <span>foo</span>
    bar
</div>'''
root = html.fromstring(raw)
texts = root.xpath('//text()[normalize-space()]')
print [t for t in texts]
# output : ['foo', '\n\tbar\n']

[html.tostring(e.getparent()) for e in texts]
# output : ['<span>foo</span>\n\tbar\n', '<span>foo</span>\n\tbar\n']
# see that calling getparent() on 'bar' returns the <span> not the <div>