Python’s mechanize to login like a user

I use a small python script to automate a user login on a site to retrieve in csv a list of other’s user linked to me.

I search a lot how to do it in python, to create a fast automated script.
Before starting you should get the mechanize (i use here the manual version (not using, you can download it here :

# -*- coding: utf-8 -*-

import sys

from mechanize import Browser

Now the import is ready, we can call pages :

	def login(br, url):
		"""login before retrieving user information"""
		page =
		#Get the form used by normal user to logon
		#send login information
		br.form["login"] = "mylogin"
		br.form["password"] = "mypassword"
		#submit form

Pretty simple so, now you can reuse br to now get access to private part to retrieve information like that (this system is using a base id/PHPSESSID to go over pages) :

	def browse(br, url, baseurl):
		"""Browse a page after passing threw login"""
		page = + url)

Just use browse with br from login, this will print each pages you ask with it like this :

br = Browser()
login(br, "")
browse(br, "", "?id=10&PHPSESSID=98bzdqd3")

That’s already finish you can now use internet site like a normal user. I personnally don’t use thread in this case to not have overload on server side (not needed to go fast for me), but you can improve this code by using a thread system to catch many pages in a row.


Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:


Vous commentez à l'aide de votre compte Déconnexion /  Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion /  Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion /  Changer )


Connexion à %s

%d blogueurs aiment cette page :