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!