How to Login by filling the form in CasperJs

ⅰ亾dé卋堺 提交于 2019-12-01 02:31:08
Shikhar
casper.waitForSelector("form input[name='name']", function() {
    this.fillSelectors('form#user-login', {
        'input[name = name ]' : 'abc@gmail.com',
        'input[name = pass ]' : 'pwd'
    }, true);
});

Simply use this (see waitForSelector docs). Firstly, wait for the form to be loaded. Then fill the form using the selectors.

casper.waitForSelector('form', function(){
    this.fill('form', {
    'name': 'abc@gmail.com', 
    'pass': 'pwd'}, true);
});

<!-- wait until a form tag disappears -->
casper.waitWhileSelector('form', function(){
    this.echo('selector is no more!');
});

casper.then(function(){
    this.echo(this.getTitle());
});

In case anyone else finds this.. I used some combination of these answers - my login form was also in an iframe which added some difficulty, but basically the issue I saw (cookie-based login) is that casper was going to the next step before the server could respond and set the cookie. I added some .wait() callbacks to ensure enough time to get that cookie. It may not be foolproof, but I have yet to have an issue with it

Mind you, the cookie needs to be set EVERY CRAWL

casper.start(config.loginUrl, function() {

console.log("Checking login status @ " + config.loginUrl);

// set a wait condition to make sure the page is loaded (particularly iframe in my case) 
this.wait(5000,function(){

    // switch to iframe (won't be necessary for most)
    this.page.switchToChildFrame('login'); 

    // fill out the form 
    this.fillSelectors("form[name='loginForm']",{
        'input#txtUsername' : config.username,
        'input#txtPassword' : config.password
    });

    // click the login button 
    console.log("Logging In...")
    this.click('input.button.login');

    // ** give my crappy dev server 5 seconds to respond
    this.wait(5000,function(){
    console.log('Starting to spider ' + dataObj.start)

    // do yo dance  
    spider(dataObj.start);
    });

Hmmm.. Follow that with:

casper.then(function () {
    this.evaluate(function () {
        $('form#user-login').submit();
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!