I'm stuck trying to get mechanize working as part of a larger project I'm working on.

I'm trying to logon to the following website which I am registered at (but not as "bob" as below obviously):


I think I've managed to select the correct form (?) but I'm getting a must assign string error from the mechanize module.

Can anyone help me out? I need to read the resulting page into a string once I've successfully logged in.

Thanks :)


#Designed to log into morningstar portfolio

from mechanize import Browser  #no need to import urllib2 as mechanize does this

urllink = 'http://www.morningstar.co.uk/uk/membership/signup.aspx?loginType=1&lastvisit=%2fuk%2fportfoliomanager%2fportfolio.aspx%3fSite%3duk%26lang%3den-GB'

br = Browser()

#for form in br.forms():
#    print form

br["ctl00$MainContent$UserName"] = ["bob"]
br["ctl00$MainContent$Password"] = ["secret123"]
response = br.submit()

print br.read()

Well, I've found an answer to my own question by using ClientForm instead of mechanize. Credit to the guy in this thread:


Code below in case anyone is interested for the future



import urllib2, cookielib, re
import ClientForm

username = "bob"
password = "secret123"
url = 'http://www.morningstar.co.uk/uk/membership/signup.aspx?loginType=1&lastvisit=%2fuk%2fportfoliomanager%2fportfolio.aspx%3fSite%3duk%26lang%3den-GB'

cookiejar = cookielib.LWPCookieJar()
cookiejar = urllib2.HTTPCookieProcessor(cookiejar)

opener = urllib2.build_opener(cookiejar)

response = urllib2.urlopen(url)
forms = ClientForm.ParseResponse(response, backwards_compat=False)

#for x in forms:
#    print x

#print forms[2]
#the 3rd form on the page (i.e. form 2 as starting at zero!) is the one we want

form = forms[2]

    form['ctl00$MainContent$UserName'] = username
    form['ctl00$MainContent$Password'] = password
except Exception, e:
    print 'The following error occured: \n"%s"' % e
    print 'A good idea is to open a browser and see if you can log in from there.'
    print 'URL:', url

page = urllib2.urlopen(form.click('ctl00$MainContent$LoginButton')).read()

print page