How to open a specific URL in a session after logi

2019-07-08 04:58发布

问题:

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);

});

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?

回答1:

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.

You need to nest the calls:

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);
    }
});

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.