我正在尝试抓取一个网站,该网站有登录页面分隔并在登录后跳转主页。这是我的代码,但我不是成就跳跃主页:
var page = require('webpage').create() ;
var login = 'https://webstie.com/login' ;
var home = 'https://website.com/home' ;
page.open(login, function (status) {
if (status !== 'success') {
console.log('fail!');
} else {
page.evaluate(function(){
function timer (f,n) {
var i = 0 ;
var t = setInterval(function(){
if (n < i) {
clearInterval(t) ;
f() ;
}
i++ ;
},50) ;
}
$("input[name=email]").val("user") ;
$("input[name=password]").val("pass") ;
$("input[type=submit]").click() ;
timer(function(){
document.location.href = home ;
timer(function(){
$('body').css('border','1px solid red') ;
},100) ;
},100) ;
}) ;
page.render('page.png') ;
}
console.log('finished!') ;
phantom.exit() ;
});
答案 0 :(得分:5)
您忘了等待异步处理。您的timer()
函数是异步的,因为setTimeout()
是异步的。这就是为什么page.render()
调用实际上在timer()
运行之前发生的原因。 phantom.exit()
也是如此。
但是您不想使用document.location.href = home
,因为那时您需要收听页面打开事件。您可以与另一个page.open()
以综合方式执行此操作。
尝试:
page.open(login, function (status) {
if (status !== 'success') {
console.log('fail!');
phantom.exit(1);
} else {
page.evaluate(function(){
$("input[name=email]").val("user") ;
$("input[name=password]").val("pass") ;
$("input[type=submit]").click() ;
});
setTimeout(function(){
page.open(home, function(status){
if (status !== "success") {
console.log('fail2');
phantom.exit(1);
return;
}
page.evaluate(function(){
$('body').css('border','1px solid red') ;
});
page.render('page.png');
console.log('finished!');
phantom.exit();
});
}, 500);
}
});
使用waitFor()
更耐用等待特定条件或使用page.onCallback
and window.callPhantom()
pair。