[SOLVED] XPath to text returning nothing?

Issue

I’m trying to address the text Aug 7, 2019 at 9:34 am ET in the following code with XPath:

<span class="meta"><span class="authordata">
<a href="https://example.com" title="Posts by me" rel="author">Author</a></span> | Aug 7, 2019 at 9:34 am ET
</span>

I use this Xpath expressions //span[@class="meta"]/text() , which always worked for me in such cases – but fail and get just emptyness.

I tried some variants too, like //span[@class="meta"]/text[0] and //span[@class="meta"]/text[1] – but failed too.

What could be the correct Xpath to Aug 7, 2019 at 9:34 am ET?

Solution

If //span[@class="meta"]/text() is not returning what you want, then there may be a text node, perhaps containing only whitespace, before your targeted text. (That expression will return all text node children of the targeted span, but in XPath 1.0 as an argument to a function requiring a string, only the first node of a node set is used.)

Since you probably don’t want the preceding | anyway, you might try calling substring-after on the string value of the parent element…

This XPath 1.0 expression,

substring-after(//span[span/a/@rel="author"],' |')

will evaluate to

Aug 7, 2019 at 9:34 am ET

as requested.

Answered By – kjhughes

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.