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):

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

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 :)

#!/usr/bin/python

#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()
br.open(urllink)

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

br.select_form(name='aspnetForm')
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:

http://bbs.archlinux.org/viewtopic.php?id=61276

Code below in case anyone is interested for the future

#!/usr/bin/python

#http://bbs.archlinux.org/viewtopic.php?id=61276
#http://wwwsearch.sourceforge.net/ClientForm/

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)
urllib2.install_opener(opener)

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]

try:
    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
    raw_input()
    exit()

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

print page
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.