Monday, April 11, 2016

CasperJS:Submit login-form with evaluate() method

Sometimes the in previous post described method of logging in to a site with casperjs  fails. That could be caused by some restrictions set server-side. Then it might be worth to try the evaluate-call in the login-script:

Example:


var casper = require('casper').create(
{
      logLevel: "info",
      verbose: "true",
      onPageInitialized: function() {
                                                 console.log('Page has been loaded successfully');
                                                 }
});

casper.userAgent('Mozilla/5.0 (compatible; Windows NT 5.0) ' );

casper.viewport = {width: 1366, height: 768};

url = 'http://www.page/login.com';

casper.start(url);

/* Next step is to fill in the credentials and submit the form
Collect id-attributes for username and password elements from source code of login-page.
*/   

casper.then(function() {
console.log('will now log in..');

this.evaluate(function() {

                                   document.getElementById("id-username").value = "username";
                                   document.getElementById("id-password-here").value = "password"
                                   document.getElementById("id-SignIn-button").click();
                                   });

/* If document.getElementById("id-signin-button").click() fails
 try document.querySelector("selector-ofSignIn-button").click();
*/

});

// wait 1 second, then take screenshot
casper.wait(1000, function() {
console.log('now taking screenshot');
casper.capture('photo1.png');
});

casper.run();