Question

I've got a script set to log into a website. The challenge is that I'm running the script on EC2 and the website is asking for me to do additional verification by sending me a custom code.

I receive the email immediately but need to be able to update that field on the fly.

This is the script

import urllib2

import urllib2
import cookielib
import urllib
import requests
import mechanize
from bs4 import BeautifulSoup

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_refresh(False)  
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

# The site we will navigate into, handling it's session
br.open('https://www.website.com/login')

#select the first form
br.select_form(nr=0)

#user credentials
br['user_key'] = 'username@gmail.com'
br['user_password'] = 'somePassw0rd'

# Login
br.submit()

#enter verification code
input_var = raw_input("Enter something: ")

#put verification code in form
br['Verication'] = str(input_var)

#submit form
br.submit()

The challenge for me is that I keep getting an error saying:

AttributeError: mechanize._mechanize.Browser instance has no attribute __setitem__ (perhaps you forgot to .select_form()?)

What can I do to make this run as intended?

Was it helpful?

Solution

after you br.submit() you go straight into

br['Verication'] = str(input_var)

this is incorrect since using br.submit() will make your browser not have a form selected anymore.

after submitting i would try:

for form in br.forms():
    print form

to see if there is another form to be selected

read up on the html code on the login site and check to see exactly what happens when you click login. You may have to reselect a form on that same page then assign the verification code to one of the controls

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top