如何仅使用lxml检索可见节点文本

时间:2015-08-15 21:44:30

标签: python lxml

如何使用Python包lxml检索节点中的可见文本,排除任何子节点或隐藏元素?

我在文档中找到的所有内容都是node.text_content(),但所有这一切都是删除html标记,无论可见性如何都会返回所有深度的所有文本。我也尝试了node.text,但似乎只为所有节点返回None。

1 个答案:

答案 0 :(得分:1)

您可以使用xpath提取所需的文本。 由于只需要可见的文本,请将/text()放在xpath中。

例如,如果我需要摘录第二段:

import requests
from lxml import etree
r = requests.get("https://stackoverflow.com/questions/32029681/how-to-retrieve-only-visible-node-text-with-lxml")
html = etree.HTML(r.text)
list_of_text = html.xpath('//*[@id="question"]/div[2]/div[2]/div[1]/p//text()') #xpath copied from browser
''.join(list_of_text)

您将获得:

'How do you use the Python package lxml to retrieve visible text in a node, excluding any child nodes or hidden elements?All I can find in the docs is node.text_content(), but all that does is strip out html tags, returning all text at all depths regardless of visibility. I also tried node.text, but that seems to just return None for all nodes.'

请注意,//text()/text()稍有不同,它将选择父节点与最后一个子节点之间的任何节点。

相关问题