我需要使用 phantomjs 从返回的 HTML 文档中 script
标记内编码的 JSON 字符串中获取特定数据。 HTML 基本上看起来像这样:
... [preamble html tags etc.]
....
<script id="ine-data" type="application/json">
{"userData": {"account_owner": "Grib"},
"skey":"b207ff1f8d5a394c2f7af1681ad3470c",
"location": "EU"
</script>
<script id="notification-data" type="application/json">
... [other stuff including html body]
我需要获取 JSON 中 skey
的值。我什至无法使用选择器访问脚本。例如,
page.open('https://www.site1.com/dash', function(status) {
var ine_data = document.querySelectorAll('script').item(0);
console.log(ine_data); phantom.exit();
});
这将返回null
。有人能指出我正确的方向吗?
最佳答案
您要查找的 PhantomJS 函数称为 page.evaluate
( documentation )。它允许您在浏览器本身的 javascript 环境中运行沙箱中的 javascript。
所以按照你的例子:
page.open('https://www.site1.com/dash', function(status) {
var ske = page.evaluate(function() {
var json_text = document.querySelector("#ine-data").innerHTML,
json_values = JSON.parse(json_text);
return json_values.skey;
});
console.log(ske)
phantom.exit();
});
尽管我注意到您示例中的 JSON 无效(缺少尾随 }
),所以如果不首先修复该问题,我的示例将无法工作!
关于javascript - 如何使用 PhantomJS 抓取嵌入的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25026803/