【问题标题】:Get code inside script tag获取脚本标签内的代码
【发布时间】:2016-07-21 07:40:53
【问题描述】:

我正在用 nodejs 和cheerio 抓取一个网站。如何获得Test 的值。

这是我正在抓取的代码。

<body>
   <div>Hello</div>
<script>
var Test = "www.example.com";
</script>
</body>

如何获取变量Test的值?

【问题讨论】:

    标签: jquery node.js cheerio


    【解决方案1】:

    你首先需要获取脚本标签的原始内容(你可以用cheerio来做),一旦你在标签里有了javascript,你就有选择:

    • 安全,但与代码结构紧密耦合:使用正则表达式查找文字值:

    var value = /\sTest\s*=\s*"([^"]*)"/.exec(js)[1]
    • 安全灵活,但更复杂(并且性能成本高)。如果代码太复杂而无法使用正则表达式,另一种方法是获取该 js 代码的 AST,然后您只需遍历 AST 即可找到您要查找的文字,您可以在此处在线尝试 Esprima了解 AST 是什么以及它的外观:http://esprima.org/demo/parse.html

    对于您分享的示例,AST 如下所示:

    var ast = {
        "type": "Program",
        "body": [
            {
                "type": "VariableDeclaration",
                "declarations": [
                    {
                        "type": "VariableDeclarator",
                        "id": {
                            "type": "Identifier",
                            "name": "Test"
                        },
                        "init": {
                            "type": "Literal",
                            "value": "www.example.com",
                            "raw": "\"www.example.com\""
                        }
                    }
                ],
                "kind": "var"
            }
        ],
        "sourceType": "script"
    }
    
    // you can use something smarter to look for "Test" variable declaration here
    var value = ast.body[0].declarations[0].init.value;
    • 不安全,令人讨厌(参见“eval is evil”),但又快又灵活:

    // assumes js code is declaring a variable named "Test"
    var value = eval(js + '; Test;');
    
    // a slightly better approach that prevents adding variables to the global scope:
    var value = eval('(function(){ ' + js + '; return Test; })();')

    大警告,如果您对该脚本标记的内容没有完全信任,则永远不要使用此 eval 方法,您会将其作为 node.js 应用程序的一部分运行,从而创建一种脚本注入漏洞。

    【讨论】:

    • 谢谢,对不起,我必须每分钟找到测试值,我知道如何设置间隔,但我不知道如何在“=”之后找到测试值
    • 我所描述的是可以做到这一点的选项,找到“=”之后的值,第一个可能是你可以尝试的最简单的,即。使用正则表达式。如果你必须重复做这一切也没关系。
    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2022-01-14
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多