简体   繁体   中英

How to login with mechanize with an jquery ajax submit form? (python)

i'm having the following problem logging in. The problem is that the site is handling the form with jQuery and ajax in this script:

function form_login()
{
    if($('#main form p.button.disabled').length) return false;

    $('#success').hide();
    $('#error').hide();

    $.post( AJAX_PATH + '/login/', $(form).serialize(), function(data) {


        if(data.result) {

            $('#success').html(data.response).show();
            setTimeout(function() { redirect(data.redirect); }, 3000);
        }
        else {

            $('#error').html(data.response).show();
            $('#login').val('');
            $('#password').val('');
            $('#main form p.button').addClass('disabled');
        }

    }, 'json');

    return false;
}

I tried to post manually with Mechanize with this code:

h = Http()
data = dict(login=user, password=password)
resp, content = h.request(url, "POST", urlencode(data))
print "Post response: " , resp

The response goes as follows:

{'status': '200', 'content-length': '3257', '-content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'server': 'nginx', 'last-modified': 'Fri, 15 Mar 2013 14:40:44 GMT', 'connection': 'keep-alive', 'etag': '"11c2203d-cb9-4d7f79fc19300;4d7f7b508f640"', 'date': 'Sun, 28 Apr 2013 23:15:07 GMT', 'content-type': 'text/html'}

What do I have to do now?

Ok, I figured out, that I have already been logged in with my code. But when I go to another page I loose my login state. So I tried not completely make a manual POST, but use mechanize. Because then it handles cookies and everything by itself. Here is what I got:

LoginUrl = "http://mywebsite.com/ajax/login/"
LoginData = dict(login=user, password=password, remember=1)
LoginHeader = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0"}
LoginRequest = urllib2.Request(LoginUrl, urlencode(LoginData))
LoginResponse = br.open(LoginRequest)

And it WORKS! :-D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM