lev*_*tov 3 javascript asynchronous phantomjs
我需要在PhantomJS中等一段时间.我搜索了很多,但没有找到答案.我在里面尝试这个代码,page.open但它不起作用.
var interval = window.setInterval(function(){
console.log("works");
clearInterval(interval);
}, 3000);
Run Code Online (Sandbox Code Playgroud)
我也试过,setTimeout但也没有帮助
window.setTimeout(function(){
console.log("works");
}, 3000);
Run Code Online (Sandbox Code Playgroud)
什么是等待几秒钟的解决方案?
我需要在日志之间等待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();
}
});
Run Code Online (Sandbox Code Playgroud)
这是错误的集合:
JavaScript没有像其他语言一样的休眠功能,因为它是单线程的.这意味着睡眠将有效地停止所有其他处理.所以,你不能使用
console.log("1");
setTimeout(function(){}, 5000);
console.log("2");
Run Code Online (Sandbox Code Playgroud)
并希望2在5秒后打印出来1.2将在之后立即打印1.您需要使用JavaScript的异步特性:
console.log("1");
setTimeout(function(){
console.log("2");
}, 5000);
Run Code Online (Sandbox Code Playgroud)phantom.exit()完成脚本后必须调用.这意味着您需要从setTimeout回调中调用它.
page.evaluate是沙盒页面上下文.您不能使用外部定义的变量.因此,您不能phantom.exit()在内部使用page.evaluate(),但您可以使用window.callPhantom/ page.onCallbackpair从页面上下文中获取消息.
如果要从页面上下文接收控制台消息,则需要提供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();
}
});
Run Code Online (Sandbox Code Playgroud)