5

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.

4

1 に答える 1

12

使用

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

これはFAQです。

説明

XPath疑似演算子は、その前のノードテストに強くバインドする演算子//よりも優先度(優先度)が低くなります。[]

数学やすべての言語と同様に、デフォルトの優先度を上書きする方法は角かっこを使用することです。

于 2012-04-11T01:53:37.247 に答える