简体   繁体   English

使用 node.js 解析 HTML 中的 JavaScript

[英]Parsing JavaScript inside HTML with node.js

I am learning to use request and cheerio to parse a simple html file.我正在学习使用 request 和cheerio 来解析一个简单的 html 文件。 However, in the page there is many script tag and inside them reside the actual data.然而,在页面中有许多脚本标签,它们内部存放着实际的数据。 For example like例如像

<script> var data = {"name":"John","age":33} </script>

So naturally the thing that is interesting is the "data" variable.所以自然有趣的是“数据”变量。 Is there a more natural way then doing regex to get that data?有没有比做正则表达式更自然的方法来获取这些数据?

With the new version jsdom(v16.4.0, nodejs 12.6.0), jsdom.jsdom doesnt exist, we can use new JSDOM like below:使用新版本 jsdom(v16.4.0, nodejs 12.6.0),jsdom.jsdom 不存在,我们可以使用新的 JSDOM,如下所示:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<script> var foo = "bar" </script>`, { runScripts: "dangerously" });
console.log(dom.window.foo);  // output is:  bar

I don't believe cheerio supports parsing inline scripts.我不相信cheerio 支持解析内联脚本。 However you can use jsdom for your use case但是,您可以将jsdom用于您的用例

var jsdom = require('jsdom')
var html = '<script>var data = {"name":"John","age":33} </script>'

jsdom.defaultDocumentFeatures = {
  FetchExternalResources: ['script'],
  ProcessExternalResources: ['script'],
  MutationEvents: '2.0',
  QuerySelector: false
}

var document = jsdom.jsdom(html)
var window = document.createWindow()
console.dir(window.data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM