使用 jQuery/cheerio 访问脚本标签中的变量

Accessing variable in script tag with jQuery/cheerio

我正在使用 node.js + cheerio 进行网络抓取。

请求网站后,我得到了这样的东西。

<html>
    <head>
        ...
    </head>
    <body>
        <script>
           var x = {name: "Jeff"};
           var y = 4;
        </script>
    </body>
</html>  

如何通过cheerio/jQuery访问变量值?

您可以将 <script> 标签内容作为文本获取,并通过正则表达式查找变量:

const cheerio = require('cheerio');
const $ = cheerio.load(html); // your html

const text = $('script')[0].text(); // TODO there might be multiple script tags

// find variable `x` in the text
const matchX = text.match(/var x = (.*);/);
console.log(matchX[1]); // prints "{name: "Jeff"}"

// find variable `y` in the text
const matchY = text.match(/var y = (.*);/);
console.log(matchY[1]); // prints "4"

您可以获得这样的字符串值。然后这取决于你想做什么,如果你需要那些对象值,你可以使用 eval (但要注意使用 eval 可能是危险的),或者你可以通过正则表达式或再次解析它一些东西(你可能知道你在寻找什么值)。