使用PhantomJS获取由Javascript呈现的html

时间:2014-09-09 08:45:32

标签: javascript html web-scraping phantomjs

我正在尝试利用PhantomJS获取动态页面生成的html。我认为这很容易,但经过几个小时的尝试,我仍然不幸运。

页面本身有这个源代码,最终保存在1.html中的内容:

<!doctype html>
<html lang="cs" ng-app="appId">
<head ng-controller="MainCtrl">
     (ommited some lines)
    <script src="/js/conf/config.js?pars"></script>
    <script src="/js/all.js?pars"></script>
</head>
<body>
<!--<![endif]-->
    <div site-loader></div>
    <div page-layout>
        <div ng-view></div>
    </div>
</body>
</html>

web的所有内容都被加载到site-loader div中,但我没有运气得到它,即使我在使用PhantomJS抓取html之前使用超时。这是我正在使用的代码:

var url = 'http:...';
var page = require('webpage').create();
var fs = require('fs');

page.open(url, function (status) {
    if (status !== 'success') {
        console.log('Fail');
        phantom.exit();
    } else {        
        window.setTimeout(function () {
        fs.write('1.html', page.content, 'w');
        phantom.exit();
        }, 2000); // Change timeout as required to allow sufficient time 
    }
});

请问我做错了什么?

编辑: 我已经决定尝试PJscrapper框架并将其配置为删除div块的所有内容。我得到的只是糟糕的:

["","\n\t\tif (window.DOT) {\n\t\t\tDOT.cfg({service: 'sreality', impress: false});\n\t\t}\n\t","","Loader.load()","",""]

似乎我认真对待它并且总是在Loader.load()行为之前获取代码。显然,超时并没有解决它。

1 个答案:

答案 0 :(得分:1)

这样就可以了解

    page.open(url, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the url!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            var results = page.evaluate(function() {
                return document.documentElement.innerHTML;
            });
            console.log(results)
            phantom.exit();
        }, 200);
    }
});