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