【发布时间】:2016-07-21 07:40:53
【问题描述】:
我正在用 nodejs 和cheerio 抓取一个网站。如何获得Test 的值。
这是我正在抓取的代码。
<body>
<div>Hello</div>
<script>
var Test = "www.example.com";
</script>
</body>
如何获取变量Test的值?
【问题讨论】:
我正在用 nodejs 和cheerio 抓取一个网站。如何获得Test 的值。
这是我正在抓取的代码。
<body>
<div>Hello</div>
<script>
var Test = "www.example.com";
</script>
</body>
如何获取变量Test的值?
【问题讨论】:
你首先需要获取脚本标签的原始内容(你可以用cheerio来做),一旦你在标签里有了javascript,你就有选择:
var value = /\sTest\s*=\s*"([^"]*)"/.exec(js)[1]
对于您分享的示例,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;
// 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 应用程序的一部分运行,从而创建一种脚本注入漏洞。
【讨论】: