xpath: How do we select just the very last text node?

两盒软妹~` 提交于 2020-01-02 05:23:10

问题


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'

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.


回答1:


Use:

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

This is a FAQ.

Explanation:

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.



来源:https://stackoverflow.com/questions/10098593/xpath-how-do-we-select-just-the-very-last-text-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!