Login to facebook com python

Asked

Viewed 4,275 times

8

I would like, for educational reason, to login to facebook with a python script. I tried with lib 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 doesn’t seem to be working. Someone has already done it?

1 answer

6


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

However there are 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, can install the robobrowser, this 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')

This last one does not need to define headers, but can. The headers of this by default are sufficient and valid for facebook.

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

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

  • Thank you so much for the reply @Miguel helped me a lot!

  • You’re welcome @Allan, thank goodness

  • 1

    The answer is absolutely correct. To complement: websites that rely heavily on dynamic content, such as twitter and facebook, in general do not lend themselves well to be accessed automatically simulating a browser - as in this case. This is why all pages will rely on javascript code to have their content displayed. These portals generally offer an API for automatic access, and for access that allows searches, posts, etc... it is best to use the API. Check out: http://facebook-sdk.readthedocs.io/en/latest/api.html https://pypi.python.org/pypi/facebook-sdk

  • Obgado @jsbueno, I just didn’t put this alternative because I didn’t think AP wanted it. I already edited adding this option. Thanks

  • Yes - when it is so, I usually give the direct answer, and write the orientation to the "correct form in general" at the end. (which is what I did in the comment above :-) ). Sometimes when what the AP is going down a very wrong path, I already start the right way of face.

  • Very Obgado @jsbueno . Here I believe that there was no mistake or right, it was only so that the AP, "for educational reasons", could 'login' on facebook via a python script

  • 1

    Yes - even if the AP knows exactly what they’re asking, it’s legl to keep in mind that the question and answer will be accessed by other people looking for similar things. And in general they will want to do it in the most direct and right way. I have a classic answer in the S.O. in English that to answer the question needs several convolutions, but the "simple" way is what 99% of people want, and it is at the end of the answer: http://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class/15247892#15247892

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.