Skip to content

Instantly share code, notes, and snippets.

Created October 3, 2015 19:46
  • Star 30 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save UndergroundLabs/fad38205068ffb904685 to your computer and use it in GitHub Desktop.
Facebook Python Login Script
import argparse
import requests
import pyquery
def login(session, email, password):
Attempt to login to Facebook. Returns user ID, xs token and
fb_dtsg token. All 3 are required to make requests to
Facebook endpoints as a logged in user. Returns False if
login failed.
# Navigate to Facebook's homepage to load Facebook's cookies.
response = session.get('')
# Attempt to login to Facebook
response ='', data={
'email': email,
'pass': password
}, allow_redirects=False)
# If c_user cookie is present, login was successful
if 'c_user' in response.cookies:
# Make a request to homepage to get fb_dtsg token
homepage_resp = session.get('')
dom = pyquery.PyQuery(homepage_resp.text.encode('utf8'))
fb_dtsg = dom('input[name="fb_dtsg"]').val()
return fb_dtsg, response.cookies['c_user'], response.cookies['xs']
return False
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Login to Facebook')
parser.add_argument('email', help='Email address')
parser.add_argument('password', help='Login password')
args = parser.parse_args()
session = requests.session()
'User-Agent': 'Mozilla/5.0 (X11; Linux i686; rv:39.0) Gecko/20100101 Firefox/39.0'
fb_dtsg, user_id, xs = login(session,, args.password)
if user_id:
print '{0}:{1}:{2}'.format(fb_dtsg, user_id, xs)
print 'Login Failed'
Copy link

Not Working In 28 Sep 2021

Copy link

Facebook change to session policy : O so is normal not working

Copy link

Can anyone specifiy why is it not working? Has facebook changed the required data we should pass with a request to login? And if so
can someone figure out what is the new data?

Copy link

I will fix and repost over the weekend. I've been away for a very long time.

Copy link

Thanks man, and welcome back.

Copy link

renelc30 commented Jul 4, 2022

is FB login doable with the facebook session policy? @UndergroundLabs ? if so I can try to make it work

Copy link

on commented May 28, 2023

is FB login doable with the facebook session policy? @UndergroundLabs ? if so I can try to make it work

it definitely is

Copy link

error: the following arguments are required: email, password
i am trying to put username and password but it gives error

Copy link

Working 2 april 2019. Thanks!

it doesn't work!!!!how it works with you ,please.??

Copy link

python-life commented Nov 24, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment