I need to extract the text from the nodes in an html file and I’m trying to use XPath and Javascript.
The required condition is that the text must contain an specific word.
Let’s take by example the next html file:
<html>
<body>
<p>
Hi, try to extract the word username here and here <b>username</b>
</p>
</body>
</html>
And try to get the text from text nodes containing the word ‘username’ with this expression:
var search = document.evaluate('//*[contains(child::text(), \"username\")]/child::text()', document, null, XPathResult.ANY_TYPE, null);
Iterating through search I’ve found the desired result but unwanted objects too:
["Hi, try to extract the word username here and here", Text, "username"]
where Text is an Object whose textContent is only the carriage return symbol (I’m using Google Chrome console). Where does this object come from?
Can anyone, please, give a more precise XPath expression that excludes those Objects or should I exclude them in my code?
The ideal search should be:
["Hi, try to extract the word username here and here", "username"]
Thanks everybody!
Looks like you want
(I’m not sure why you’re escaping your double quotes inside single quotes, but that’s a separate issue.)
Your existing code,
says,
The (1) part of the expression will return element nodes
<p>and<b>.For the (2) step,
<b>has only one text node child, but<p>has two: the one before the<b>(which contains “username”) and the one after the<b>(which contains only whitespace).Solution: Forget about elements — they are an irrelevant distraction. Just select the desired text nodes directly.