views:

37

answers:

2

Could someone help me or share some code to auto fill a login with mechanize (http://wwwsearch.sourceforge.net/mechanize/)? I want to make a python script to log me into my favorite sites when I run it.

Thanks!

+1  A: 

This will help you to login to one site and download a page for example:

import mechanize
br=mechanize.Browser()
br.open('http://www.yourfavoritesite.com')
br.select_form(nr=0) #check yoursite forms to match the correct number
br['Username']='Username' #use the proper input type=text name
br['Password']='Password' #use the proper input type=password name
br.submit()
br.retrieve('https://www.yourfavoritesite.com/pagetoretrieve.html','yourfavoritepage.html')

This script presumes that your login form is the first of the page and the input names are Username and Password.
You could also select your form by name with:

br.select_form(name="thisthing")

Please, adapt this script to your favorite site login page.
As well pointed by AlexMartelli, this script should be generalized to handle different sites with some config parameters.

systempuntoout
urhm, what do you mean by forms number? you mean like the name of the form in html? and what does retrieve do?`<form action="bleh.php" name="thisthing"/>`
@shorty see my edit
systempuntoout
one more thing how do i know if the log in succeded?
@shorty you should be able to download the private page :)
systempuntoout
A: 

Each of your favorite sites probably has different forms (form number, and names of user and password fields) and one hopes you use different usernames and passwords on each (using the same user and password on many sites means that if one of the sites is cracked, your identity is now compromised "everywhere" -- quite a mess!).

So, you can either hardcode all of these parameters, as in @systempuntoout's answer, or write a little configuration text file (for example in the format supported by ConfigParser) with all this info for each site, so that you can load the configuration when your script starts, and write a "log_me_in" function, just once, that takes the sitename as the parameter and looks up and uses the parameters that depend on it.

If you have a lot of "favorite sites", so that loading all their info perceptibly slows your startup time, then you may even want to consider persisting that info more smartly (e.g. in a sqlite table) so it can be looked up rapidly for just one or a few sites given their names as the "key" to use.

Alex Martelli