有没有办法抓取网站并在每个页面上抓取JavaScript变量?

时间:2013-09-26 19:51:18

标签: javascript xpath phantomjs rapidminer adobe-analytics

我工作的公司将在几个月后重新设计网站,我们需要的一件事就是包含网站上每个网页的每个网址的表格。然后,最佳地,会有列包含一组预定义JavaScript变量的值(在这种情况下,Omniture变量,因此我们可以确保每个页面都正确标记其在站点层次结构中的位置)。

以下是给定页面的HTML内容的示例:

<script type="text/javascript">     
metrics_level2  = "biz";
metrics_level3  = "products";
metrics_level4  = "my_awesome_product";
metrics_pagename    = "biz|products|my_awesome_product";    
</script>

我已经使用RapidMiner抓取了网站并且数据准备好了,但我的问题是隔离这些变量并将“metrics_level2”,“metrics_level3”等放在他们自己的列中的最佳方法。 XPath是最好的方法吗?常用表达?我对XPath的尝试似乎在标签之间引入了全部内容,这需要在事后进行大量清理。

1 个答案:

答案 0 :(得分:4)

如果你使用PhantomJS http://phantomjs.org/,你可以像在网页中一样使用JavaScript访问这些变量。一个非常简单的例子如下:

//where url is the page that contains these variables.
page.open(url, function (status) {
    //Page is loaded!
    var dataFromPage = page.evaluate(function(){
       return {
                 metrics_level2:metrics_level2,
                 metrics_level3:metrics_level3,
                 metrics_level4:metrics_level4
              };
    });
    //dataFromPage now contains those variables

    phantom.exit();
});

如果您已将网页抓取并保存到html文件或其他内容,则可以使用content方法设置页面对象的内容,如上所示打开页面。见http://phantomjs.org/api/webpage/property/content.html