xpath:我们如何仅选择最后一个文本节点? [英] xpath: How do we select just the very last text node?

查看:138
本文介绍了xpath:我们如何仅选择最后一个文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用xpath选择全局最后的文本节点? 我尝试了此操作,但它为我提供了文档每个上下文中的最后一个节点.

How do I select the globally-last text node using xpath? I tried this, but it gives me the last node in every context of the document.

lxml.html.fromstring('1<a>2<b>3</b>4<c>5</c>6</a>').xpath('//text()[last()]')
['1', '3', '5', '6']

我可以这样做,但是它在时间和空间上都效率低下,尤其是当文档变大时.

I can do this, but it's inefficient in both time and space, especially as the document gets large.

lxml.html.fromstring('1<a>2<b>3</b>4<c>5</c>6</a>').xpath('//text()[last()]')[-1]
'6'

我尝试使用索引-1,但这给了我一个空列表.我尝试使用一些反向轴(以便可以使用1进行索引),但无法使它们在全局环境下工作.

I tried to use an index of -1, but that gives me an empty list. I tried to use some of the reverse axes (so that I could index with 1), but I couldn't get them to work in a global context.

推荐答案

使用:

(//text())[last()]

这是一个常见问题解答.

This is a FAQ.

说明:

XPath伪运算符//的优先级(优先级)比[]运算符低,该运算符更强地绑定到其前面的节点测试.

The XPath pseudo-operator // has a lower precedence (priority), than the [] operator, which binds stronger to the node-test preceding it.

在数学和每种语言中,覆盖默认优先级的方法是使用方括号.

As in Math and in every language, the way to override default priority is by using brackets.

这篇关于xpath:我们如何仅选择最后一个文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆