2015-07-10 2 views
0

Я пишу функцию, чтобы ждать элемента, вот моя функция:Ожидание элемента без SetTimeout в PhantomJS

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(), я называю эту функцию и результат «нулевой». Но если я ставлю вызов функции в setTimeout(), он будет работать.

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

Может кто-нибудь объяснить мне, что здесь произошло?

ответ

0

Обратный вызов page.open вызывается только при загрузке страницы. Это не означает, что все было загружено на вашу страницу, и js был полностью выполнен.

Кроме того, js на веб-странице может не выполняться немедленно, особенно если сайт использует клиентские среды MVC, такие как AngularJS или Backbone.js. Многое происходит после события загрузки страницы.

Использование setTimeout дает вам небольшую задержку, чтобы быть уверенным, что ваша страница полностью отображена.

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); 
Смежные вопросы