【问题标题】:How to find text's Parent Node?如何找到文本的父节点?
【发布时间】:2016-06-01 22:27:04
【问题描述】:

如果我使用:

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')]

是否可以到达被搜索文本的网页元素?

【问题讨论】:

  • 我认为 BeatuifulSoup 对你来说是一个更好的选择。

标签: python parsing web-scraping python-requests lxml


【解决方案1】:

您可以为此目的使用 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()将返回前面的元素。请参阅下面的示例以清楚地了解我一直在谈论的内容:

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>

【讨论】:

  • 您好,解决方案有效。非常感谢您的帮助。
猜你喜欢
  • 2011-03-21
  • 2010-12-08
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 2015-03-30
相关资源
最近更新 更多