How to extract text separated by different HTML tags in Cheerio
P粉141911244
P粉141911244 2023-08-13 17:01:06
0
2
556
<p>I'm trying to extract the following specific text strings as separate outputs, for example (grabbing them from the HTML below): </p> <pre class="brush:js;toolbar:false;">let text = "This is the first text I need"; let text2 = "This is the second text I need"; let text3 = "This is the third text I need"; </pre> <p>I really don't know how to get text separated by different HTML tags. </p> <pre class="brush:html;toolbar:false;"><p> <span class="hidden-text"><span class="ft-semi">Count:</span>31<br></span> <span class="ft-semi">Something:</span> This is the first text I need <span class="hidden-text"><span class="ft-semi">Something2:</span> </span>This is the second text I need <br><span class="ft-semi">Something3:</span> This is the third text I need </p> </pre> <p><br /></p>
P粉141911244
P粉141911244

reply all(2)
P粉198670603

Try something like this and see if it works:

html = `your sample html above`

domdoc = new DOMParser().parseFromString(html, "text/html")
result = domdoc.evaluate('//text()[not(ancestor::span)]', domdoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

for (let i = 0; i < result.snapshotLength; i++) {
  target = result.snapshotItem(i).textContent.trim()
  if (target.length > 0) {
    console.log(target);
  }
}

Using your example html, the output should be:

"That's the first text I need"
"The second text I need"
"The third text I need"
P粉386318086

You can iterate over the child nodes of <p> and get the nodeType === Node.TEXT_NODE:

for any non-empty content

for (const e of document.querySelector("p").childNodes) {
  if (e.nodeType === Node.TEXT_NODE && e.textContent.trim()) {
    console.log(e.textContent.trim());
  }
}

// 或者创建一个数组:
const result = [...document.querySelector("p").childNodes]
  .filter(e =>
    e.nodeType === Node.TEXT_NODE && e.textContent.trim()
  )
  .map(e => e.textContent.trim());
console.log(result);
<p>
  <span class="hidden-text">
    <span class="ft-semi">Count:</span>
    31
    <br>
  </span>
  <span class="ft-semi">Something:</span>
  That's the first text I need
  <span class="hidden-text">
    <span class="ft-semi">Something2:</span>
  </span>
  The second text I need
  <br>
  <span class="ft-semi">Something3:</span>
  The third text I need
</p>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!