• 如何用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先翻墙把这个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值。

  • 相关阅读:
    css
    bootstrap
    在线小工具
    文档工具-Markdown
    js
    棋盘问题(深搜,统计)
    ****Curling 2.0(深搜+回溯)
    POJ 2676 Sudoku(深搜)
    POJ 2488 A Knight's Journey(深搜+回溯)
    ural 1104. Don’t Ask Woman about Her Age
  • 原文地址:https://www.cnblogs.com/dodng/p/5387959.html
Copyright © 2020-2023  润新知