Sunday, 18 July 2021

Can't log in to facebook using requests module

I'm trying to log in to facebook using requests module. Although it seems I've prepared payload in the right way but when I send it with post requests, I don't get desired content in the response. I get 200 status code, though. To let you know, If I get response accordingly, I should find my fullname within it.

I initially tried like the following:

import requests
from bs4 import BeautifulSoup
from datetime import datetime

link = 'https://www.facebook.com/'
base_url = 'https://www.facebook.com{}'

time = int(datetime.now().timestamp())

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
    'referer': 'https://www.facebook.com/',
}

with requests.Session() as s:
    r = s.get(link)
    soup = BeautifulSoup(r.text,"lxml")
    form_url = soup.select_one("form[data-testid='royal_login_form']")['action']
    post_url = base_url.format(form_url)
    payload = {i['name']:i.get('value','') for i in soup.select('input[name]')}
    payload['email'] = 'YOUR_EMAIL'
    payload['encpass'] = f'#PWD_BROWSER:0:{time}:YOUR_PASSWORD'
    payload.pop('pass')
    res = s.post(post_url,data=payload,headers=headers)
    print(res.url)
    print(res.text)

This is another way I tried which didn't work out either:

import requests
from bs4 import BeautifulSoup
from datetime import datetime

login_url = 'https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=101'
time = int(datetime.now().timestamp())

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'origin': 'https://www.facebook.com',
    'referer': 'https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=101'
}

with requests.Session() as s:
    r = s.get(login_url)
    soup = BeautifulSoup(r.text,"lxml")
    payload = {i['name']:i.get('value','') for i in soup.select('input[name]')}
    payload['email'] = 'YOUR_EMAIL'
    payload['encpass'] = f'#PWD_BROWSER:0:{time}:YOUR_PASSWORD'
    payload['had_password_prefilled'] = 'true'
    payload['had_cp_prefilled'] = 'true'
    payload['prefill_source'] = 'browser_dropdown'
    payload['prefill_type'] = 'contact_point'
    payload['first_prefill_source'] = 'last_login'
    payload['first_prefill_type'] = 'contact_point'
    payload['prefill_contact_point'] = 'YOUR_EMAIL'
    payload.pop('pass')
    r = s.post(login_url,data=payload,headers=headers)
    print(r.status_code)
    print(r.url)

How can I log in to facebook using requests?



from Can't log in to facebook using requests module

No comments:

Post a Comment