如何用phantomjs去抓取js渲染后的页面

1.安装phantomjs

网上有很多。

 

2.执行官网上的示例代码

// Read the Phantom webpage '#intro' element text using jQuery and "includeJs"

"use strict";
var page = require('webpage').create();

page.onConsoleMessage = function(msg) {
    console.log(msg);
};

page.open("http://phantomjs.org/", function(status) {
    if (status === "success") {
        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
            page.evaluate(function() {
                console.log("$(\".explanation\").text() -> " + $(".explanation").text());
            });
            phantom.exit(0);
        });
    } else {
      phantom.exit(1);
    }
});

  

3.执行状态为一直卡在那里,不报错也不退出

为了查看程序的内部执行状态,加入运行日志

                page.onResourceRequested = function (req) {
                                console.log('requested: ' + JSON.stringify(req, undefined, 4));
                                    };  

                    page.onResourceReceived = function (res) {
                                    console.log('received: ' + JSON.stringify(res, undefined, 4));
                                        };  

  

4.发现程序一直卡在一个js的请求

http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js

5.在自己的服务器上用python的SimpleHTTPServer 简单搭了一个http的server先FQ把这个js下载下来,放到web上


6.修改代码把includeJS指向自己搭的http server上






备注:


调试过程发现phantomjs还有一个问题,就是page.open是异步执行的,如下代码:

var webPage = require('webpage');
var page = webPage.create();

page.open('http://www.baidu.com/', function(status) {
                  console.log('Status: ' + status);
                    // Do other things here...
                     }); 

phantom.exit(1)

你执行完后,打印返回值,echo $?,会得到1

 

而你把

phantom.exit(1)

注释之后,会得到status值。

posted @ 2016-04-13 17:29  dodng  阅读(12512)  评论(0编辑  收藏  举报