【问题标题】:Accessing variable in script tag with jQuery/cheerio使用 jQuery/cheerio 访问脚本标签中的变量
【发布时间】:2018-04-04 15:08:09
【问题描述】:

我正在使用 node.js + Cheerio 进行网页抓取。

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

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

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

【问题讨论】:

    标签: javascript jquery node.js cheerio


    【解决方案1】:

    您可以将&lt;script&gt; 标记内容作为文本获取,然后通过正则表达式查找变量:

    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可能很危险),或者你可以通过正则表达式或其他东西再次解析它(你可能知道你在寻找什么价值观)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      相关资源
      最近更新 更多