[javascript] phantomjsでコンテンツが表示されるまで待つ
phantomjsでコンテンツが表示されるまで待つ
phantomjsはブラウザレスでJavascriptを実行できるので便利だが、全部のJavascriptが処理終了するまでは待ってくれないので、以下のコードで、あるコードが表示されるまで待たせる
250msごとにページ状態を確認し、最大3秒待つ。
#thedivがvisibleだったら「The sign-in dialog should be visible now.」と表示させ、処理を終了させる
"use strict";
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://xxxx.com/test.php", function (status) {
if (status !== "success") {
console.log("Unable to access network");
} else {
console.log("Start Wait");
waitFor(function() {
return page.evaluate(function() {
return $('#thediv').is(':visible');
});
}, function() {
console.log("visible now.");
phantom.exit();
});
}
});
応用:
もし
タグが表示されたら、次の処理に移りたい場合は
waitFor(function() {
return page.evaluate(function() {
return $('#thediv').is(':visible');
});
}, function() {
console.log("visible now.");
phantom.exit();
});
を
waitFor(function() {
return page.evaluate(function() {
return document.getElementsByTagName('h2')[0].innerHTML != null;
});
}, function() {
console.log("visible now.");
phantom.exit();
});
に変える