Phantomjs将waitfor与includeJs集成在一起

时间:2015-05-19 20:52:09

标签: javascript jquery phantomjs

我可以使用示例中提供的waitfor函数 https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js 我也可以使用这里提供的includeJ http://phantomjs.org/page-automation.html

我很难弄清楚如何在waitfor函数中包含jquery。

下面的sudo代码只是我尝试过的众多内容之一。请帮忙。

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 250); //< repeat check every 250ms
};


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

page.open("http://example.com", function (status) {
    if (status !== "success") {
        console.log("Unable to access network");
    } else {
        waitFor(function() {
            // This does not work
            page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
                return page.evaluate(function() {
                    return $("#some-element").is(":visible");
                });
            });    
        }, function() {
           console.log("some-element should be visible now.");
           phantom.exit();
        });        
    }
});

1 个答案:

答案 0 :(得分:0)

正如您在waitFor()代码中看到的那样,testFx函数每250毫秒调用一次。该函数应该只包含实际的检查代码而不包含加载代码。只需将includeJs()来电移出testFx即可。另请注意,testFx函数必须返回它在示例中没有的内容,因此它总是未定义,并且在一段时间后会超时。

page.open("http://example.com", function (status) {
    if (status !== "success") {
        console.log("Unable to access network");
    } else {
        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
            waitFor(function() {
                return page.evaluate(function() {
                    return $("#some-element").is(":visible");
                });
            }, function() {
               console.log("some-element should be visible now.");
               phantom.exit();
            });
        });
    }
});