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

Fahem Moz

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

请求网站后,我得到了类似的东西。

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

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

马丁·阿达梅克

您可以将<script>标签内容作为文本获取,然后通过regexp查找变量:

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可能很危险),也可以通过regexp或其他方式再次对其进行解析(您可能知道要查找的值)对于)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章