how to wait for element visibility in phantomjs

后端 未结 4 1498
予麋鹿
予麋鹿 2020-11-29 02:58

Users click this link:


Now I\'m simulating the click i

4条回答
  •  甜味超标
    2020-11-29 03:26

    My approach for this scenario is to wait until "something" is done or true. I highly suggest you to test waitfor.js.

    demo.html

    
    
    
        
        Test
    
    
    
        
    Hello World !

    demoscript.js

    var page = require('webpage').create();
    var system = require('system');
    
    function waitFor(testFx, onReady, timeOutMillis) {
        var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 5000, //< Default Max Timout is 5s
            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");
                        typeof (onReady) === "string" ? eval(onReady) : onReady();
                        clearInterval(interval);
                        //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
                    }
                }
            }, 500); //< repeat check every 500ms
    };
    
    if (system.args.length != 1) {
        console.log('invalid call');
        phantom.exit(1);
    } else {
        //adapt the url to your context
        page.open('http://localhost:40772/demo.html', function (status) {
            if (status !== 'success') {
                console.log('Unable to load the address!');
                phantom.exit();
            } else {
                waitFor(
                    function () {
                        return page.evaluate(function () {
                            return $('#thediv').is(':visible');
                        });
                    },
                    function () {
                        page.render('page.png');
                        phantom.exit();
                    }, 5000);
            }
        });
    }
    

    This script evaluate $('#thediv').is(':visible')(classic Jquery code) every 500 ms to check if the div is visible.

提交回复
热议问题