search

Home  >  Q&A  >  body text

How to extract text separated by different HTML tags in Cheerio

<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粉141911244P粉141911244499 days ago616

reply all(2)I'll reply

  • P粉198670603

    P粉1986706032023-08-14 14:15:14

    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"

    reply
    0
  • P粉386318086

    P粉3863180862023-08-14 13:23:13

    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>

    reply
    0
  • Cancelreply