Auto-login in python using mechanize
<p>I have an almost working code to connect to a server and do a search. But there is some issue here with the code. This is what I do now with the following python script. I login to the site. Construct a url for the search result and access the search page and open it in a browser. But issue I am facing here is that I am getting a session expired page. But if I have a logged in page open(manually) in the browser, this constructed url is giving me the desired output. So my question here is that How can I keep the 'logged in' session in the script active and open the constructed url in a browser which yield me the desired output.</p>

<pre><code>#!/usr/bin/env python

import urllib, urllib2, cookielib, mechanize, webbrowser, subprocess
from mechanize import ParseResponse, urlopen, urljoin

def main():
    usr = 'sg092350'
    pwd = 'gk530911'
    login_url = 'http://int15.sla.findhere.net/logininq.act?&amp;site=superarms'

    search_url_1 = '&amp;need_air=yes&amp;need_rail=no&amp;need_train=no&amp;need_hotel=no&amp;need_car=no&amp;origin_request=regular+booking&amp;monAbbrList[0]=9&amp;monAbbrList[1]=9&amp;dateList[0]=29&amp;dateList[1]=30&amp;pickUpCity=&amp;pickUpTime=&amp;dropOffCity=&amp;dropOffTime=&amp;dispAOptions=&amp;dispADestinations=&amp;checkSurroundingAirports=false&amp;doEncodeDecodeForSurrArpt=false&amp;checkPlusMinusDays=N&amp;tripType=roundTrip&amp;itinType=on&amp;departList[0]=BLR&amp;destinationList[0]=DEL&amp;date0=9%2F29%2F11&amp;travelMethodList[0]=departs&amp;timeList[0]=8&amp;date1=9%2F30%2F11&amp;travelMethodList[1]=departs&amp;timeList[1]=8&amp;numPassengers=1&amp;cabinClass=1&amp;pricingType=1&amp;preferredCarrier[0]=&amp;preferredCarrier[1]=&amp;preferredCarrier[2]=&amp;userRequestedWebFares=true'



    br = mechanize.Browser()
    cj = cookielib.CookieJar()

    br.set_cookiejar(cj)
    br.set_handle_robots(False)

    br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2')]

    br.open(login_url)
    br.select_form('loginForm')

    br.form['user'] = usr
    br.form['pwd'] = pwd

    br.submit()
    print br.geturl()

    response = urlopen(login_url)
    forms = ParseResponse(response, backwards_compat=False)
    form = forms[0]
    token = forms[0]['token']
    site_id = forms[0]['siteID']
    site = forms[0]['site']
    water_mark = forms[0]['watermark']
    trans_index = forms[0]['transIndex']


    search_url_0 = 'http://int15.sla.findhere.net/pwairavail.act;' + '?site=' + site + '&amp;sid=4' + '&amp;siteID=' + site_id + '&amp;watermark=' + water_mark + '&amp;token=' + token + '&amp;transIndex=' + trans_index + search_url_1
    print search_url_0

    print token
    print site_id
    print site
    print water_mark
    print trans_index

    print form

    response.read()

    #Inserting code to generate html and display the overlay

    htmlString = """
    &lt;html&gt;
    &lt;head&gt;
    &lt;title&gt;DirectBook 1.0&lt;/title&gt;
    &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="./fx/jquery.fancybox-1.3.4.pack.js"&gt;&lt;/script&gt;
    &lt;link rel="stylesheet" type="text/css" href="./fx/jquery.fancybox-1.3.4.css" media="screen"/&gt;
    &lt;script type="text/javascript"&gt;
    $(document).ready(function() {
    $("#urlLink").fancybox
    ({
    'width'      : '100%',
    'height'      : '100%',
    'autoScale'      : false,
    'transitionIn'   : 'fade',
    'transitionOut'   : 'fade',
    'type'      : 'iframe'
    });
    });
    &lt;/script&gt;
    &lt;/head&gt;
    &lt;body onload="document.getElementById('urlLink').click()"&gt;
    &lt;div id="content"&gt;
    &lt;script type="text/javascript"&gt;
    var search_url = " """ + search_url_0 + """ ";
    document.write('&lt;a id="urlLink"' + 'href="' + search_url + '"&gt;&lt;/a&gt;');
    &lt;/script&gt;
    &lt;/div&gt;
    &lt;/body&gt;
    &lt;/html&gt;"""


    # write the html file to the working folder
    fout = open("search.html", "w")
    fout.write(htmlString)
    fout.close()

    subprocess.Popen('"C:\\Program Files\\Mozilla Firefox\\firefox.exe" "C:\\Python27\\mechanize-0.2.5\\search.html"')


if __name__ == '__main__':
    main()
</code></pre>
