-1

I want to extract the text from <p><strong>Some text</strong></p>and using Cheerio in Node.JS.

I have the following code: $('p > strong').text() but it does not output anything.

console.log($('p > strong').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><strong>Some text</strong></p>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
quieri
  • 345
  • 3
  • 19
  • 3
    The code you provided appears to work as-is, what are you expecting? – APAD1 Jul 11 '19 at 18:17
  • Is the string also available without javascript? you are not able to use elements that are generated dynamically with cheerio. – BlakkM9 Jul 11 '19 at 18:18
  • I hope, you will understand my code and then convert it to your own, document.getElementById('Id Name').textContent; or innerHTML. Similiar link https://stackoverflow.com/questions/34709765/cheerio-how-to-select-element-by-text-content – Ericgit Jul 11 '19 at 18:19
  • This seems to work: https://repl.it/repls/CompatibleIroncladTheory – Get Off My Lawn Jul 11 '19 at 18:30
  • Here we go! https://itnext.io/scraping-with-nodejs-and-cheerio-d4d34e2cf – Ericgit Jul 11 '19 at 18:31

2 Answers2

2

Your code looks fine (and works fine). See this: https://jsfiddle.net/mswilson4040/2m3c1kpn/

There's probably something specific to Cheerio here which is hard to determine based off the code provided. We need some more context

When you run your code, are you getting any error messages? More than likely, you're javascript is executing before the dom has loaded, or you're referencing your javascript file before the element you're after has loaded.

For a basic troubleshooting step, try executing this line of code:

console.log($('p > strong'))

That should give you an idea if your jquery call is even getting the element or not. If it's not, then that is the problem.

mwilson
  • 12,295
  • 7
  • 55
  • 95
  • Confusing OP using cheerio in headless browser with jQuery – charlietfl Jul 11 '19 at 18:21
  • I use this to extract data from a API call and I use async and await before I proceed to extract the data. Maybe there is some difference for Cheerio? – quieri Jul 11 '19 at 18:23
  • There probably is. Can you post a little bit more code so I can get more context? I'll update my answer – mwilson Jul 11 '19 at 18:24
0

I think I got it to work as I wanted by using below:

$('strong', 'p').text()

Thank you everyone for your help!

quieri
  • 345
  • 3
  • 19