在PhantomJS中登录后如何在会话中打开特定的URL [英] How to open a specific URL in a session after login in PhantomJS
问题描述
我正在使用PhantomJS登录到Facebook.这是我的代码:
I'm loging in to facebook with PhantomJS. Here is my code:
var page = require('webpage').create();
phantom.cookiesEnabled = true;
page.open("http://www.facebook.com/login.php", function(status) {
if (status === "success") {
page.evaluate(function() {
document.getElementById("email").value = "email";
document.getElementById("pass").value = "pass";
document.getElementById("loginbutton").click();
});
window.setTimeout(function() {
page.render("page.png");
phantom.exit();
}, 5000);
}
});
page.open("https://www.facebook.com/myprofil", function(status) {
window.setTimeout(function() {
page.render("profil.png");
phantom.exit();
}, 5000);
});
到目前为止,登录过程可以正常进行,但是例如在同一会话中,我没有找到访问我的个人资料URL的正确方法.我尝试再次使用page.open,但是我一直在获取请求页面的登录表单,好像以前从未登录过一样.在您的会话中进行导航的正确方法是什么?
so far so good the login process goes fine, but I didn't find the right method to visit my profile URL for example in the same session. I tried to use page.open again, but I keep getting the login form with the page I requested as if I never logged in before. What's the proper way to navigate within your session?
推荐答案
page.open
是异步函数.打开页面需要一些时间.完成后,将调用回调.如果连续两次调用page.open
而不等待第一个调用完成,则实际上是在覆盖第一个请求,因此将仅执行第二个请求.
page.open
is an asynchronous function. It takes some time to open a page. When it's done, the callback is called. If you're calling page.open
twice in a row without waiting for the first call to be finished, you're essentially overwriting the first request, so only the second one will be executed.
您需要嵌套通话:
page.open("http://www.facebook.com/login.php", function(status) {
if (status === "success") {
page.evaluate(function() {
document.getElementById("email").value = "email";
document.getElementById("pass").value = "pass";
document.getElementById("loginbutton").click();
});
window.setTimeout(function() {
page.render("page.png");
page.open("https://www.facebook.com/myprofil", function(status) {
window.setTimeout(function() {
page.render("profil.png");
phantom.exit();
}, 5000);
});
}, 5000);
}
});
请记住,一旦调用phantom.exit()
,PhantomJS就会退出.因此,当脚本应该结束时,您应该只有一个phantom.exit()
.
Remember that PhantomJS exits as soon as phantom.exit()
is called. So you should probably have a single phantom.exit()
when your script is supposed to end.
这篇关于在PhantomJS中登录后如何在会话中打开特定的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!