我需要在PhantomJS中等待一段时间。我搜索了很多,但没有找到答案。我在page.open
里面尝试了这段代码,但它不起作用。
var interval = window.setInterval(function(){
console.log("works");
clearInterval(interval);
}, 3000);
我也尝试了setTimeout
但也无济于事
window.setTimeout(function(){
console.log("works");
}, 3000);
等待几秒钟的解决方案是什么?
我需要在日志之间等待 3 秒:jquery included
和 works
.但这些日志同时显示在控制台中。
var page = require("webpage").create();
var url = "https://www.youtube.com";
page.open(url, function(status) {
if (status == "success"){
console.log(status);
if (page.injectJs("jquery.min.js")){
console.log("jquery included");
page.evaluate(function(){
setTimeout(function(){
}, 3000);
});
console.log("works");
phantom.exit();
}
}
else{
console.log(status);
phantom.exit();
}
});
这是错误的集合:
-
JavaScript 不像其他语言那样有睡眠函数,因为它是单线程的。这意味着睡眠将有效地停止所有其他处理。所以,你不能使用
console.log("1"); setTimeout(function(){}, 5000); console.log("2");
并期望
2
在1
后 5 秒打印。2
将在1
后立即打印。你需要使用 JavaScript 的异步特性:console.log("1"); setTimeout(function(){ console.log("2"); }, 5000);
完成 脚本后必须调用
phantom.exit()
。这意味着您需要从setTimeout
回调调用它。page.evaluate
是沙盒页面上下文。不能使用外部定义的变量。因此,您不能在page.evaluate()
中使用phantom.exit()
,但您可以使用window.callPhantom
/page.onCallback
对从页面上下文中获取消息。如果要从页面上下文接收控制台消息,则需要提供
onConsoleMessage
事件处理程序。
完整脚本:
var page = require("webpage").create();
var url = "https://www.youtube.com";
page.onCallback = function(data){
if (data.type === "exit") {
phantom.exit();
}
};
page.onConsoleMessage = function(msg){
console.log("remote: " + msg);
};
page.open(url, function(status) {
if (status == "success"){
console.log(status);
if (page.injectJs("jquery.min.js")){
console.log("jquery included");
page.evaluate(function(){
setTimeout(function(){
console.log("works");
window.callPhantom({type: "exit"});
}, 3000);
});
}
}
else{
console.log(status);
phantom.exit();
}
});