20

I am using the cheerio lib and am trying to get this script field - script type="application/json" But for some reason it can not find these script tags. What is wrong? How do I fix?

var $ = require('cheerio')
var parsedHTML = $.load(html)
console.log( parsedHTML('script').get().length ); // this is 0
CWon
  • 241
  • 1
  • 2
  • 7

2 Answers2

31

If you use

var parsedHTML = $.load('<html><head><script type="application/json" src="http://myscript.org/somescript.ks"></script></head></html>')
console.log( parsedHTML('script').get()[0].attribs['src'] ); 

You can fetch a url and then use the request to fetch the contents

If you want to get at an inline script, you can do this:

console.log( parsedHTML('script').get()[0].children[0].data ); 
Abhinav Singi
  • 3,133
  • 1
  • 15
  • 27
Gervase
  • 930
  • 8
  • 15
4

To those still wandering into this thread, the following solution worked for me:

const $ = cheerio.load(html, {xmlMode: false});
$('script').length; // no longer 0

(See htmlparser2's options)

user137794
  • 1,559
  • 2
  • 7
  • 9