title: Using Python mechanize to log into websites?
body: <p>I'm using mechanize (<a href="http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/" rel="nofollow">and following this tutorial</a>) to try to log into websites. I wanted to try to test it out on Twitter, so this is the script I came up with:</p>
  
  <pre><code>import mechanize
  import cookielib
  
  username = 'user'   # your username/email
  password = 'pass'   # your password
  
  br = mechanize.Browser()
  
  # set cookies
  cookies = cookielib.LWPCookieJar()
  br.set_cookiejar(cookies)
  
  # browser settings (used to emulate a browser)
  br.set_handle_equiv(True)
  br.set_handle_redirect(True)
  br.set_handle_referer(True)
  br.set_handle_robots(False)
  br.set_debug_http(False)
  br.set_debug_responses(False)
  br.set_debug_redirects(False)
  br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time = 1)
  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.open('http://twitter.com/') # open twitter
  
  br.select_form(nr=1) # select the form
  
  br['session[username_or_email]'] = username
  br['session[password]'] = password
  br.submit() # submit the login data
  print(br.response().read) # print the response
  </code></pre>
  
  <p>Here is the Python output from when I run my script:</p>
  
  <pre><code>$ python twitterLoginTest.py 
  &lt;bound method response_seek_wrapper.read of &lt;response_seek_wrapper at 0x8feaeac whose wrapped object = &lt;closeable_response at 0x8feeaac whose fp = &lt;socket._fileobject object at 0x8feb42c&gt;&gt;&gt;&gt;
  </code></pre>
  
  <p>(the name of the file is twitterLoginTest.py)</p>
  
  <p>Now, I'm not really sure what that response means, but it doesn't really seem correct.</p>
  
  <p>So here are my questions</p>
  
  <p>1) Is there a better way of logging into websites using scripts (not just twitter, but any website, and a method that could be modified to work on any website with a log in)?</p>
  
  <p>2) Where am I going wrong in my script?</p>
  
  <p>3) How can I fix the problem, to login?</p>
  
  <p>I have a hypothesis that the problem is stemming from <code>br.select_form(nr=1)</code> (that's where I select the form), but I didn't know what to put there (so I figured it would be the second form) because Twitter doesn't name their forms.</p>