Log in to a webpage using phantomjs and jQuery

I am new to phantomjs, Java script and WebScraping in general. What I want to do is basic HTTP authentication, and then visit a different URL to get some information. Here is what I have so far. Please tell me what I am doing wrong.

var page = require('webpage').create();
var system = require('system');

page.onConsoleMessage = function(msg) {
   console.log(msg);
};

page.onAlert = function(msg) {
   console.log('alert!!>' + msg);
};

page.settings.userName = "foo";
page.settings.password = "bar";

page.open("http://localhost/login", function(status) {
    console.log(status);
    var retval = page.evaluate(function() {
       return "test";
    });
    console.log(retval);

    page.open("http://localhost/ticket/" + system.args[1], function(status) {
        if ( status === "success" ) {
            page.injectJs("jquery.min.js");
            var k = page.evaluate(function () {
                var a = $("div.description > h3 + p");

                if (a.length == 2) {
                    console.log(a.slice(-1).text())
                } 
                else {
                    console.log(a.slice(-2).text())
                }
            //return document.getElementById('addfiles');
            });

        }
    });
    phantom.exit();
});

I pass an argument to this file: ticket number, which is added to the second URL.

+5
source share
1 answer

I would recommend CasperJS for this.

CasperJS - , Javascript, PhantomJS - WebKit. , , :

  • ( )
  • DOM
  • , .
  • , JUnit XML
  • -

( - CasperJS)

, PhantomJS , - .

CasperJS API-, :

http://docs.casperjs.org/en/latest/modules/casper.html#fill

var casper = require('casper').create();

casper.start('http://some.tld/contact.form', function() {
    this.fill('form#contact-form', {
        'subject':    'I am watching you',
        'content':    'So be careful.',
        'civility':   'Mr',
        'name':       'Chuck Norris',
        'email':      'chuck@norris.com',
        'cc':         true,
        'attachment': '/Users/chuck/roundhousekick.doc'
    }, true);
});

casper.then(function() {
    this.evaluateOrDie(function() {
        return /message sent/.test(document.body.innerText);
    }, 'sending message failed');
});

casper.run(function() {
    this.echo('message sent').exit();
});
+9

All Articles