Log in to Facebook using python requests

I am trying to find a way to automatically log in to Facebook without a browser using Python. I experimented with lib requests. I tried several ways:

URL = 'http://m.facebook.com' requests.get(URL, auth = ('email@domain.com', 'mypassword')) 

...

 form_data = {'email': 'email@domain.com', 'pass' : 'mypassword' } requests.post(URL, data = form_data) 

...

 requests.post(URL + '?email=email@domain.com&pass=mypassword') 

The last method fills in the "email" field on the page, but the "transfer" field remains empty ...

Can someone help me with this please? Is it possible to emulate FB logging using queries?

Thank!

+30
python facebook python-requests facebook-login
Feb 21 '14 at 7:48
source share
10 answers

You need to send the full form. The easiest way to find out what Facebook expects is to use the Google Chrome Developer Tools to track your web requests.

To simplify your life, I tracked my own Facebook login and reproduced it below (with personal information edited, obviously), with non-essential information:

 Request URL:https://m.facebook.com/login.php?refsrc=https%3A%2F%2Fm.facebook.com%2F&refid=8 Request Method:POST Form Data: lsd:AVqAE5Wf charset_test:€,´,€,´,水,,Є version:1 ajax:0 width:0 pxr:0 gps:0 m_ts:1392974963 li:cxwHUxatQiaLv1nZEYPp0aTB email:... pass:... login:Log In 

As you can see, the form contains many fields. All must be provided so that you can enter. Email and password will be provided with your code. The rest of the fields actually have their own HTML values ​​that Facebook serves you. This means that in order to emulate the browser login, you need to follow these steps:

  • Make a GET on the login page ( https://m.facebook.com/ )
  • Use an HTML parsing library (such as BeautifulSoup) to parse HTML and find the default values ​​of form fields.
    • The default values ​​are in the <input> HTML elements under the #login_form element. You will want to find them by name (e.g. charset_test ) and then pull out their value attribute.
    • Developing how to do this is beyond the scope of this answer, so I'm not going to go into it.
  • Combine the default values ​​of the form fields with your email and password, for example:

     data = { 'lsd': lsd, 'charset_test': csettest, 'version': version, 'ajax': ajax, 'width': width, 'pxr': pxr, 'gps': gps, 'm_ts': mts, 'li': li, } data['email'] = email data['pass'] = pass data['login'] = 'Log In' 
  • Submit your username using the Session request:

     s = requests.Session() r = s.post(url, data=data) r.raise_for_status() 
  • Send all your future HTTP traffic through Session .

As you can see, this is a non-trivial way of doing things. This is because programs were not expected to use the website to log in: instead, you should use the SDK or their web API .

+23
Feb 21 '14 at 9:43
source share

I was also looking for an answer. Doing this with requests is a pain. So, I used mechanize.

 import mechanize browser = mechanize.Browser() browser.set_handle_robots(False) cookies = mechanize.CookieJar() browser.set_cookiejar(cookies) browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7')] browser.set_handle_refresh(False) url = 'http://www.facebook.com/login.php' self.browser.open(url) self.browser.select_form(nr = 0) #This is login-password form -> nr = number = 0 self.browser.form['email'] = YourLogin self.browser.form['pass'] = YourPassw response = self.browser.submit() print response.read() 

It works. mechanize.browser is an emulated browser, so you do not need to submit all form values. He will send them as a normal browser, you must specify only the username and password.

Good luck

+14
Jun 27 '15 at 17:59 on
source share

A library like RoboBrowser makes it easy to log in to Facebook:

 import robobrowser class Facebook(robobrowser.RoboBrowser): url = 'https://facebook.com' def __init__(self, email, password): self.email = email self.password = password super().__init__() self.login() def login(self): self.open(self.url) login_form = self.get_form(id='login_form') login_form['email'] = self.email login_form['pass'] = self.password self.submit_form(login_form) 
+6
Jun 22 '16 at 2:02
source share

Here is my working code (May 2017 Python 3.6). For this to work for you, just copy your own USERNAME, PASSWORD and PROTECTED_URL

 # https://gist.github.com/UndergroundLabs/fad38205068ffb904685 # this github example said tokens are also necessary, but I found # they were not needed import requests USERNAME = '-----@yahoo.com' PASSWORD = '----password' PROTECTED_URL = 'https://m.facebook.com/groups/318395378171876?view=members' # my original intentions were to scrape data from the group page # PROTECTED_URL = 'https://www.facebook.com/groups/318395378171876/members/' # but the only working login code I found needs to use m.facebook URLs # which can be found by logging into https://m.facebook.com/login/ and # going to the the protected page the same way you would on a desktop def login(session, email, password): ''' Attempt to login to Facebook. Returns cookies given to a user after they successfully log in. ''' # Attempt to login to Facebook response = session.post('https://m.facebook.com/login.php', data={ 'email': email, 'pass': password }, allow_redirects=False) assert response.status_code == 302 assert 'c_user' in response.cookies return response.cookies if __name__ == "__main__": session = requests.session() cookies = login(session, USERNAME, PASSWORD) response = session.get(PROTECTED_URL, cookies=cookies, allow_redirects=False) assert response.text.find('Home') != -1 # to visually see if you got into the protected page, I recomend copying # the value of response.text, pasting it in the HTML input field of # http://codebeautify.org/htmlviewer/ and hitting the run button 
+3
May 15 '17 at 15:55
source share

First of all, you need ALL of these forms. You can’t just send the password of user +, the server will not allow it.
Secondly, you will need to take care and use the cookies received from Facebook for this to work.

But overall, yes, you can use request or any other library.
But I would recommend using their APIs instead.

+2
Feb 21 '14 at 7:58
source share

I can say that it is very annoying to log into Facebook without using my API. They also like to change things so often that it's a good job of maintaining code.

I did this a while ago, but I don’t think my code is speeding up with the current Facebook. However, this should be a useful starting point:

https://gitorious.org/blogsmashonfb/blogsmashonfb/source/4f7ee94a56fdffe9392485df8999e340f97f4bbe :

It consists of two parts: a web browser and a Facebook handler (the latter interests you).

One of the main problems that you have in your code is that you must first visit Facebook, because they send you an login form with hidden elements that you need to send back.

+1
Feb 21 '14 at 9:38
source share

As others say, using queries is a pain. You can do this using selenium. Install selenium by going to their site or simply not using it.

 pip install -U selenium 

I wrote the code below. I tried it myself and it works.

 from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary(r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe') driver = webdriver.Firefox(firefox_binary=binary) driver.get('https://www.facebook.com/') username= "your_username" password = "your_password" UN = driver.find_element_by_id('email') UN.send_keys(username) PS = driver.find_element_by_id('pass') PS.send_keys(password) LI = driver.find_element_by_id('loginbutton') LI.click() 
+1
Nov 10 '16 at 13:00
source share

It works (April 2017)

 #!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import datetime import json import logging import re import random import requests import shutil from pyquery import PyQuery as pq def main(username, password): logging.basicConfig(filename='imgur2fb.log', level=logging.DEBUG) session = requests.session() uid, dtsg = login(session, username, password) def login(session, username, password): ''' Login to Facebook ''' # Navigate to the Facebook homepage response = session.get('https://facebook.com') # Construct the DOM dom = pq(response.text) # Get the lsd value from the HTML. This is required to make the login request lsd = dom('[name="lsd"]').val() # Perform the login request response = session.post('https://www.facebook.com/login.php?login_attempt=1', data={ 'lsd': lsd, 'email': username, 'pass': password, 'default_persistent': '0', 'timezone': '-60', 'lgndim': '', 'lgnrnd': '', 'lgnjs': '', 'locale':'en_GB', 'qsstamp': '' }) ''' Get the users ID and fb_dtsg token. The fb_dtsg token is required when making requests as a logged in user. It never changes, so we only need to grab this token once. If the login was successful a cookie 'c_user' is set by Facebook. If the login failed, the 'c_user' cookie will not be present. This will raise an exception. ''' try: uid = session.cookies['c_user'] dtsg = re.search(r'(type="hidden" name="fb_dtsg" value="([0-9a-zA-Z-_:]+)")', response.text).group(1) dtsg = dtsg[dtsg.find("value")+6:] dtsg = dtsg[1:-1] except KeyError: raise Exception('Login Failed!') return uid, dtsg try: main(username='*****', password='*****') except Exception, e: logging.exception(e) print e 
0
Apr 18 '17 at 13:24
source share

First you need to know the data to publish. Follow this link .

After you get all the necessary data, the code is as follows:

 import requests, bs4' s = requests.Session() url = 'https://www.facebook.com/login' res = s.get(url) form_data = { # Copy paste the form data here as a valid python dict } s.post(url, data=form_data) # Now try accessing your profile from sessions object 

It worked for me.

0
Jun 11 '18 at 9:22
source share

Read this. Here is the correct explanation for logging into Facebook using Python

0
Jul 25 '19 at 7:17
source share



All Articles