PhantomJS page.evaluate在url重定向后不起作用

时间:2015-02-07 20:23:39

标签: javascript phantomjs url-redirection

我将以下JavaScript代码保存在文件名 ph_test.js 中。

var page;
var args = require('system').args;
var url_str = 'http://'+args[1];

var renderPage = function(){

    page = require('webpage').create();
    var myArgs = Array.prototype.slice.call(arguments),
        url_str = myArgs[0];

    // Set the viewport size
    page.viewportSize = {
        width: 320,
        height: 480
    };

    // Sets the User Agent
    page.settings.userAgent = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7';

    /**
     * From PhantomJS documentation:
     * This callback is invoked when there is a JavaScript console. The callback may accept up to three arguments:
     * the string for the message, the line number, and the source identifier.
     */
    page.onConsoleMessage = function (msg, line, source) {
        console.log('console> ' + msg);
    };

    /**
     * From PhantomJS documentation:
     * This callback is invoked when there is a JavaScript alert. The only argument passed to the callback is the string for the message.
     */
    page.onAlert = function (msg) {
        console.log('alert!!> ' + msg);
    };

    /**
     * Handle Redirection
     */
    page.onNavigationRequested = function(url_sub_str, type, willNavigate, main) {
        if (main && url_sub_str != url_str)
        {
            url_str = url_sub_str;
            console.log("redirect caught");
            page.close();
            renderPage(url_str);
        }
    };

    /**
     * Open the web page and run RRunner
     */
    page.open(url_str, function(status) {
        if (status === 'success') {
            page.injectJs('https://code.jquery.com/jquery-1.11.2.min.js');

            // Our "event loop"
            if(!phantom.state)
            {
                phFunction(url_str);
            }
            else {
                phantom.state();
            }
        }
        else
        {
            console.log('failed');
        }

        page.close();
        setTimeout(function(){
            phantom.exit();
        }, 1000);

        function phFunction()
        {
            var myArgs = Array.prototype.slice.call(arguments),
                url_str = myArgs[0]
                ;

            page.evaluate(function (url_str) {
                console.log('evaluate');
            }, url_str);

            page.render('screenshots/screenshot_full.png');
        }
    });
};

renderPage(url_str);

当我运行以下命令[指向我的网站]时:

phantomjs ph_test.js www.restive.io

一切正常,没有问题。但是,当我将它运行到另一个具有移动重定向的网站[在这种情况下是淘宝]

 phantomjs ph_test.js www.taobao.com

page.evaluate没有运行,因为我看不到消息'评估'在我的控制台中。

注意:我使用的是PhantomJS 1.9.8。

0 个答案:

没有答案