How to make PhantomJS wait for a specific conditio

2019-08-11 05:04发布

问题:

I want to realize something like this:

function(){
     var ua = page.evaluate(function() {
         while (document.getElementById("td_details87").parentElement.children[11].textContent == "Running" ) {
              console.log ("running.....");
              sleep(10000); //10 seconds
         }; 
         console.log ("DONE");
     });
},

How can I realize the sleep function and is there a while loop?

回答1:

There is no blocking sleep() function in JavaScript. If you want to sleep then you have to use some asynchronous function like setTimeout(callback, timeout).

There is a function in the examples folder of PhantomJS that does what you're trying to do. It's waitFor(testFx, onReady[, timeout]). It works by calling the test function over and over again until it returns a truthy value.

In your case that would look like this:

waitFor(function _test(){
    return page.evaluate(function() {
        return document.getElementById("td_details87").parentElement.children[11].textContent == "Running"; 
    });
}, function _onReady(){
    console.log ("DONE");
});