Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 498
bukzor Avatar asked Apr 11 '12 01:04

bukzor


People also ask

How do I find the XPath of text?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.

What is the difference between DOT and text in XPath?

enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node.

Can you use XPath with HTML?

XML and HTML Note that HTML and XML have a very similar structure, which is why XPath can be used almost interchangeably to navigate both HTML and XML documents.


1 Answers

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.

like image 145
Dimitre Novatchev Avatar answered Sep 21 '22 18:09

Dimitre Novatchev