在PhantomJS中等待没有setTimeout的元素

时间:2015-07-10 03:40:57

标签: javascript phantomjs settimeout

我正在编写一个等待元素的函数,这是我的函数:

function waitForElement(query){
    var res="null";
    var start=Date.now();
    do{
        res=page.evaluate(function(query) {
            return document.querySelector(query)+"";
        }, query);
    } while (res==="null" && Date.now()-start<=100000);
    console.log(Date.now()-start);
    console.log(res.toString());
    return res!=="null";
}

page.open()中,我调用此函数,结果为&#34; null&#34;。但是,如果我将函数调用放在setTimeout()中,它就可以工作。

setTimeout(function(){
    page.render('afterLogin.png');
    waitForElement('ul.coach li');
    console.log('Exit');
    phantom.exit();
}, 50000);

有人可以向我解释这里发生了什么吗?

2 个答案:

答案 0 :(得分:2)

JavaScript是单线程的。由于您正忙着等待,您还会阻止执行页面加载和页面JavaScript。在PhantomJS中无法同步等待。您必须使用递归和异步方法,如waitFor.js PhantomJS示例文件夹中所示:

/**
 * Wait until the test condition is true or a timeout occurs. Useful for waiting
 * on a server response or for a ui change (fadeIn, etc.) to occur.
 *
 * @param testFx javascript condition that evaluates to a boolean,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param onReady what to do when testFx condition is fulfilled,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
 */
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
};

你可以像这样使用它:

function waitForElement(selector, callback, timeout){
    waitFor(function check(){
        return page.evaluate(function(selector){
            return !!document.querySelector(selector);
        }, selector);
    }, callback, timeout);
}

setTimeout(function(){
    page.render('afterLogin.png');
    waitForElement('ul.coach li', function(){
        console.log('Exit');
        phantom.exit();
    }, 100000);
}, 50000);

答案 1 :(得分:0)

仅在加载页面时调用page.open回调。这并不意味着页面中已加载了所有内容,并且js已完全执行。

此外,网页上的js可能不会立即执行,特别是如果该站点使用AngularJS或Backbone.js等MVC客户端框架。在页面加载事件之后完成了很多工作。

使用setTimeout会有一点延迟,以确保您的页面完全呈现。