How to get script content using cheerio

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

 var $ = require('cheerio') var parsedHTML = $.load(html) console.log( parsedHTML('script').get().length ); // this is 0 
+11
javascript npm cheerio
source share
2 answers

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 get the URL and then use the request to get the content

If you want a built-in script, you can do this:

 console.log( parsedHTML('script').get()[0].children[0].data ); 
+14
source share

For those still wandering around this topic, the following solution worked for me:

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

(See htmlparser2 options )

+1
source share

All Articles