Search code examples
pythontwitterauthenticationmechanize

Using Python mechanize to log into websites?


I'm using mechanize (and following this tutorial) 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:

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

Here is the Python output from when I run my script:

$ python twitterLoginTest.py 
<bound method response_seek_wrapper.read of <response_seek_wrapper at 0x8feaeac whose wrapped object = <closeable_response at 0x8feeaac whose fp = <socket._fileobject object at 0x8feb42c>>>>

(the name of the file is twitterLoginTest.py)

Now, I'm not really sure what that response means, but it doesn't really seem correct.

So here are my questions

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)?

2) Where am I going wrong in my script?

3) How can I fix the problem, to login?

I have a hypothesis that the problem is stemming from br.select_form(nr=1) (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.


Solution

  • I believe the last line should be:

    print(br.response().read()) # print the response
    

    Notice the () after read. You are currently just printing the read method itself, not the result of calling the read method.