Login on facebook with python

6

I would like, for educational reasons, to log into facebook with a python script. I tried the requests

import requests

s = requests.Session()
post_url = 'https://www.facebook.com/login.php?login_attempt=1&lwv=110'

headers = {"User-agent" : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'}
login_data = {'email': 'USERNAME', 'pass': 'PASSWORD'}
pag_formulario = s.post(formulario_url, headers=headers, data=login_data)

But it does not seem to be working. Has anyone done this yet?

    
asked by anonymous 26.07.2016 / 21:51

1 answer

5

With requests (only) it is difficult to log in to facebook, even because they should bet on javascript to generate additional data for security, and it would be very tricky to track everything that happens. In addition you must send (post method) all values of the form. I know this because I have already tried it and it did not just result with requests.

However you have other modules that can help.

For python > = 2.4 and < 3 (python 2.x), you can use mechanize :

import mechanize

url = 'https://m.facebook.com'
loggedin_title = 'Facebook' # isto vai servir para confirmarmos que estamos loggedin, vendo o titulo da pagina para onde fomos redirecionados 
username = 'USERNAME'
password = 'PASSWORD'

browser = mechanize.Browser()
browser.set_handle_robots(False)
browser.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6)')]

browser.open(url)
browser.select_form(nr=0)
browser.form["email"] = username
browser.form["pass"] = password
browser.submit()

if browser.title() == loggedin_title:
    print '[+] SUCCESS'
    print 'Username: {}\nPassword: {}'.format(username, password)
else:
    print '[-] LOGIN FAILED'

For python > = 3, you can install or robobrowser , it also makes use of the requests module:

import robobrowser
import re

url = 'https://m.facebook.com'
loggedin_title = 'Facebook' # isto vai servir para confirmarmos que estamos loggedin, vendo o titulo da pagina para onde fomos redirecionados 

browser = robobrowser.RoboBrowser(history=True, parser='html.parser')
browser.open(url)

form = browser.get_form(id='login_form')
form['email'].value = 'USERNAME'
form['pass'].value = 'PASSWORD'
browser.submit_form(form, submit=form['login'])

redirect_title = re.compile('<title>(.*?)</title>').search(str(browser.parsed)).group(1)

if(redirect_title == loggedin_title):
    print('[+] SUCCESS')
    print('Username: {}\nPassword: {}'.format(form['email'].value, form['pass'].value))
else:
    print('[-] LOGIN FAILED')

In the latter you do not have to define headers, but you can. The default headers are sufficient and valid for facebook.

Note that this code is only stable until facebook changes the login mechanics, if this happens it will have to be adapted

Here has the 'official' alternative offered by facebook itself.

    
26.07.2016 / 21:58