Search code examples
javascriptphantomjscasperjs

CasperJS login form wait success


I try login in the page:

var casper = require('casper').create();
casper.start('http://sprashivai.ru/', function() {
    this.click('#signin_link');

    this.capture('foo.jpg', undefined, {
        format: 'jpg',
        quality: 75
    });

    this.fillSelectors('form', {
        '#signin_username' : 'admin@*****',
        '#signin_pass' : '*****'
    }, true);

    casper.then(function() {
        this.capture('foo_2.jpg', undefined, {
            format: 'jpg',
            quality: 75
        });
    });

    casper.thenOpen(function() {
        this.capture('foo_3.jpg', undefined, {
            format: 'jpg',
            quality: 75
        });
    });

    casper.then(function() {
        this.capture('foo_4.jpg', undefined, {
            format: 'jpg',
            quality: 75
        });
    });

    this.waitForSelector("#top_nq_badge",
        function pass () {
            test.pass("Found #top_nq_badge");
        },
        function fail () {
            test.fail("Did not load element #top_nq_badge");
        },
        20000 // timeout limit in milliseconds
    );
});


casper.run();

I know that after login I can see element #top_nq_badge, but waitForSelector not work for me. How I can login with CasperJS on the page?

I run the script: $ casperjs secr.js And it nothing print, script success worked without errors.

foo_3.jpg and foo_4.jpg files not created by script. But my foo.jpg and foo_2.jpg screenshots:

foo.jpg

foo_2.jpg


Solution

  • There is no test variable, to catch an error about it, you need to use .on('error' callback, Loading of the selector #top_nq_badge is very slowly.

    var casper = require('casper').create({
        verbose: true,
        logLevel: 'debug',
        waitTimeout: 5000,
        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',
        viewportSize:{width: 1600, height: 900}
    })
    .on('error', function(msg) {
        this.echo('Error: ' + msg, "ERROR");
    })
    .on('remote.message', function(msg) {this.echo('The error from evaluate: ' + msg, "ERROR");})
    .start('http://sprashivai.ru/', function() {
        this
        .click('#signin_link');
        this.wait(0,function(){var i=0;
        function snap(){i++;casper.capture('foo_'+i+'.jpg', undefined,{format: 'jpg',quality: 75});if(i<4){setTimeout(snap,1000)}}snap();
        })
        .fillSelectors('form', {
            '#signin_username' : '<login_here>',
            '#signin_pass' : '<pass_here>'
        }, true)
        .waitForSelector("#top_nq_badge",
        function success() {
            this
                .echo('logged in!', 'INFO')
                .capture('in.png')
        },
        function fail(){
            this
                .capture('failed.png')
                .echo('failed to login', 'ERROR');
        })
    })
    .run()