Python - Problems using mechanize to log into a difficult website

Posted by user1781599 on Stack Overflow See other posts from Stack Overflow or by user1781599
Published on 2012-10-28T22:57:03Z Indexed on 2012/10/28 23:00 UTC
Read the original article Hit count: 173

Filed under:

× 139886 I am trying to log in to betfair.com by using mechanize. I have tried several ways but it always fail. This is the code I have developed so far, can anyone help me to identify what is wrong with it and how I can improve it to log into my betfair account? Thanks,

import cookielib
import urllib
import urllib2
from BeautifulSoup import BeautifulSoup
import mechanize
from mechanize import Browser
import re

bf_username_name =  "username" 
bf_password_name =  "password" 
bf_form_name = "loginForm"
bf_username = "xxxxx"
bf_password = "yyyyy"
urlLogIn = "http://www.betfair.com/"
accountUrl = "https://myaccount.betfair.com/account/home?rlhm=0&" # This url I will use to verify if log in has been successful

br = mechanize.Browser(factory=mechanize.RobustFactory())

br.addheaders = [("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.90 Safari/537.1")]

br.open(urlLogIn)

br.select_form(nr=0)

print br.form

br.form[bf_username_name] = bf_username
br.form[bf_password_name] = bf_password

print br.form #just to check username and psw have been recorded correctly

responseSubmit = br.submit()
response = br.open(accountUrl)

text_file = open("LogInResponse.html", "w")
text_file.write(responseSubmit.read()) #this file should show the home page with me logged in, but it show home page as if I was not logged it
text_file.close()

text_file = open("Account.html", "w")
text_file.write(response.read()) #this file should show my account page, but it should a pop up with an error
text_file.close()

© Stack Overflow or respective owner

Related posts about python