繁体   English   中英

node.js解析html文本以获取javascript变量的值

[英]node.js parsing html text to get a value to a javascript variable

我成功完成了此操作,以获取感兴趣页面的帮助文本。

router.get('/get', function (req, res) {
    var pg = 'https://j......com/f/resource'
    console.log('get', pg);
    requestify.get(pg).then(function (resp) {
        console.log(resp.body);
    });
});

现在我有了页面的文本,我想解析文本以获取我知道该文本中存在的javascript变量的值。

<script> var x1 = {"p": {.......bla bla ...}};</script>

我知道有时候<script>标签会包含type属性; 但它并不总是包含type属性。

当我找到x1的值时,我将在我的javascript应用程序中使用什么作为myVar变量中的值。

如果您没有答案,那么您对我应该研究的内容的评论/提示将不胜感激。

我希望能找到一些模块,我可以将整个文本放入其中,并让该模块以某种方式为我输出所有变量和值。

因此,您不必重新发明轮子,我觉得使用JSDOM (及其执行功能)将是最好的选择。 模拟您所拥有的:

const express   = require('express');
const jsdom     = require("jsdom");
const { JSDOM } = jsdom; // it exports a JSDOM class

// Mock a remote resource
const remote = express()
  .use('/', (req, res) => {
    res.send('<!DOCTYPE html><html lang="en-US"><head><title>Test document</title><script>var x1 = { "p": { "foo": "bar" } };</script></head><body></body></html>');
  })
  .listen(3001);

// Create "your" server
const local = express()
  .use('/', (req, res) => {
    // fetch the remote resource and load it into JSDOM. No need for
    // requestify, but you can use the JSDOM ctor and pass it a string
    // if you're doing something more complex than hitting an endpoint
    // (like passing auth, creds, etc.)
    JSDOM.fromURL('http://localhost:3001/', {
      runScripts: "dangerously" // allow <script> to run
    }).then((dom) => {
      // pass back the result of "x1" from the context of the
      // loaded dom page.
      res.send(dom.window.x1);
    });
  })
  .listen(3000);

然后我收到回信:

{"p":{"foo":"bar"}}

暂无
暂无

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

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