如何使用PhantomJS刮取嵌入式JSON

时间:2014-07-30 00:00:53

标签: javascript json web-scraping phantomjs

我需要使用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。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

您正在寻找的PhantomJS功能称为page.evaluatedocumentation)。它允许您在浏览器本身的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是无效的(缺少一个尾随的}),所以如果没有先修复它,我的例子将无法工作!

相关问题