How to login into a website with CasperJS?

前端 未结 2 1838
粉色の甜心
粉色の甜心 2020-12-02 08:36

How can I login with CasperJS by submitting a form. I searched google and haven\'t found any good examples about it.

2条回答
  •  长情又很酷
    2020-12-02 09:34

    Here is a slightly changed version of the code from Ngo Hung. The selector for the username was off as was the assignment of the userAgent:

    var casper = require('casper').create({   
        verbose: true, 
        logLevel: 'debug',
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22',
        pageSettings: {
          loadImages:  false,         // The WebPage instance used by Casper will
          loadPlugins: false         // use these settings
        }
    });
    
    // 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 = 'http://www.facebook.com/';
    
    casper.start(url, function() {
        console.log("page loaded");
        this.test.assertExists('form#login_form', 'form is found');
        this.fill('form#login_form', { 
            email: '****', 
            pass:  '****'
        }, true);
    });
    
    casper.thenEvaluate(function(){
        console.log("Page Title " + document.title);
        console.log("Your name is " + document.querySelector(".fbxWelcomeBoxName").innerHTML);
    });
    
    casper.run();
    

    UPDATE: I recommend anyone else to use a site of their own, or at least not facebook.com if they are planning large amounts of testing. Facebook could tell that I was trying to log in over and over started emailing me and making me confirm my account with SMS.

提交回复
热议问题