简体   繁体   中英

Automating Login using python mechanize

so this is my first time programming ever and I'm trying to automate logging into a website using python/mechanize. So this is my code:

import mechanize
import cookielib

# 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_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)

# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)


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')]

br.add_password('http://newiso.accellion.net/w', 'USERNAME', 'PASSWORD')
br.open('http://newiso.accellion.net/w')


# Show the html title
print br.title()

# Show the response headers
print br.response().info()

# Show the available forms
for f in br.forms():
   print f

br.form["g_username"] = "USERNAME"
br.form["password"] = "PASSWORD"

import urllib
opener = urllib.FancyURLopener()
print opener.open('http://USERNAME:PASSWORD@newiso.accellion.net/').read()

and I keep getting this error:

Traceback (most recent call last):
File "/Users/dancetrina/Documents/login.py", line 45, in <module>
br.form["g_username"] = "USERNAME"
TypeError: 'NoneType' object does not support item assignment

does that mean that I can't use mechanize to type in the username/password? Or is there something I'm missing that would make it work? Thank you so much in advance!

In the last (and only :-) ) for loop, you should write:

f.form["g_username"] = "USERNAME"
f.form["password"] = "PASSWORD"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM