javascript 如何使用cheerio获取脚本内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24565800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do get script content using cheerio
提问by CWon
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?
我正在使用cheerio lib并试图获取此脚本字段 -script type="application/json"
但由于某种原因它找不到这些脚本标签。怎么了?我该如何解决?
var $ = require('cheerio')
var parsedHTML = $.load(html)
console.log( parsedHTML('script').get().length ); // this is 0
回答by Gervase
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
您可以获取一个 url,然后使用该请求来获取内容
If you want to get at an inline script, you can do this:
如果你想获得一个内联脚本,你可以这样做:
console.log( parsedHTML('script').get()[0].children[0].data );
回答by user137794
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)