Search code examples
linkedin-apicasperjs

CasperJS to login to LinkedIn


I am using this code to login to LinkedIn using casperJS but its not working, the title after login should be "Welcome! LinkedIn" but its returning "World's Largest Professional Network | LinkedIn" and the document.location should be different than website url but its returning website url after execution.

var casper = require('casper').create({   
verbose: true, 
logLevel: 'debug',
pageSettings: {
     loadImages:  false,         // The WebPage instance used by Casper will
     loadPlugins: false,         // use these settings
     userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
}
});

// print out all the messages in the headless browser context
casper.on('remote.message', function(msg) {
    this.echo('remote message caught: ' + msg);
});

// print out all the messages in the headless browser context
casper.on("page.error", function(msg, trace) {
    this.echo("Page Error: " + msg, "ERROR");
});

var url = 'https://www.linkedin.com/';

casper.start(url, function() {
   // search for 'casperjs' from google form
   console.log("page loaded");
   this.test.assertExists('form#login', 'form is found');
   this.fill('form#login', { 
        session_key: '[email protected]', 
        session_password:  'password'
    }, true);
});

casper.thenEvaluate(function(){
   console.log("Page Title " + document.title);
   console.log("Your name is " + document.location ); 
});

casper.run();

What am I doing wrong in this code?


Solution

  • I think that the script evaluate the code too fast.

    So i'll replace casper.thenEvaluate with this sentences (if you are running your script with casper 1.1) :

     casper.waitForUrl(/nhome/, function() {
          this.evaluate(function() {
              console.log("Page Title " + document.title);
              console.log("Your name is " + document.location ); 
          });
     });
    

    Also, you can try it with wait

     casper.wait(2000, function() {
          this.evaluate(function() {
              console.log("Page Title " + document.title);
              console.log("Your name is " + document.location ); 
          });
     });
    

    More information about this function : http://docs.casperjs.org/en/latest/modules/casper.html#waitforurl