Как авторизоваться в Facebook через cookies?

Я пытаюсь авторизоваться в фэйсбук используя рабочий куки., чтобы получить токен. Через Selenium работает все замечательно. Но работает все крайне долго. Поэтому я решил использовать requests в Python. Ниже представлен мой код(куки подпорчу слегка):
import requests
cookies = {
    'fb-cookies' : '[{"domain":".facebook.com","expirationDate":1715770896.0,"httpOnly":true,"name":"datr","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":null,"value":"Di-CYkcNBJfcNpLAFbz_Arwl","id":1},{"domain":".facebook.com","expirationDate":1684840969.0,"httpOnly":false,"name":"c_user","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":null,"value":"100080947256553","id":1},{"domain":".facebook.com","expirationDate":1653391384.0,"httpOnly":false,"name":"cppo","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":null,"value":"1","id":1},{"domain":".facebook.com","expirationDate":-62135568000.0,"httpOnly":false,"name":"presence","path":"/","sameSite":"no_restriction","secure":true,"session":true,"storeId":null,"value":"C%7B%22t3%22%3A%5B%5D%2C%22utc3%22%3A1653304958149%2C%22v%22%3A1%7D","id":1},{"domain":".facebook.com","expirationDate":1684840969.0,"httpOnly":true,"name":"xs","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":null,"value":"29%3AIxSOr-p12bK3iA%3A2%3A1652698925%3A-1%3A-1%3A%3AAcXzOdBD6kyrTjfaLrJDNCNySTGu_JoNhT86e6poAA","id":1},{"domain":".facebook.com","expirationDate":1661080968.0,"httpOnly":true,"name":"fr","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":null,"value":"0YFKcsFGS0YsUgc0K.AWWb4YErlGnkV_TBVliP_O3lt1w.Bii26K.tC.AAA.0.0.Bii26K.AWXVapQxHwM","id":1},{"domain":".facebook.com","expirationDate":-62135568000.0,"httpOnly":false,"name":"usida","path":"/","sameSite":"no_restriction","secure":true,"session":true,"storeId":null,"value":"eyJ2ZXIiOjEsImlkIjoiQXJjYzJhZzFhNHBxOHIiLCJ0aW1lIjoxNjUzMzA0OTg0fQ%3D%3D","id":1}]'
}


url = "https://www.facebook.com/adsmanager/manage"

headers = {
    'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0'
}

response = requests.get(url, cookies=cookies)
print(response.headers)


Что-то делаю не так, потому что токен так и не достал, ниже укажу заголовки, может вы поймете, что не так:
'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'Set-Cookie': 'fb-cookies=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=-1654508490; path=/; domain=www.facebook.com; httponly, fb-cookies=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=-1654508490; path=/; domain=facebook.com; httponly, fb-cookies=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=-1654508490;

Меня смущает "fb-cookies"-deleted

К слову, когда открываешь страницу менеджера в фэйсбук, она какое-то время прогружается и уже после выдает нужную страницу.
Как используя куки можно получить токен?
  • Вопрос задан
  • 1419 просмотров
Решения вопроса 1
Dunaevlad
@Dunaevlad
def face_token():
    """Get TOKEN"""
    from bs4 import BeautifulSoup
    import httpx
    import ssl
    
    uri = "https://www.facebook.com/adsmanager/manage"
    ctx = ssl.create_default_context()
    client = httpx.Client(verify=ctx)
    r = client.get(
        url=uri,
        headers={
            "Host": "www.facebook.com",
            "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.5",
            "Accept-Encoding": "gzip, deflate",
            "Referer": "https://www.facebook.com/index.php?next=https%3A%2F%2Fwww.facebook.com%2Fadsmanager%2Fmanage",
            "Connection": "keep-alive",
            "Cookie": "cookies_there",  # use the cookies that you receive after logging into your account
            "Upgrade-Insecure-Requests": "1",
            "Sec-Fetch-Dest": "document",
            "Sec-Fetch-Mode": "navigate",
            "Sec-Fetch-Site": "same-origin",
            "Sec-Fetch-User": "?1",
            "TE": "trailers",
        },
    )
    print("[* Response headers]\n", r.headers)
    # From headers you can get => privacy_mutation_token(see x-fb-debug) =
    # "eyJ0eXBlIjowLCJjcmVhdGlvbl90aW1lIjoxNjU0NzE4MTg0LCJjYWxsc2l0ZV9pZCI6MzgxMjI5MDc5NTc1OTQ2fQ=="
    # use it for POST https://www.facebook.com/login/?privacy_mutation_token=
    # eyJ0eXBlIjowLCJjcmVhdGlvbl90aW1lIjoxNjU0NzE4MTg0LCJjYWxsc2l0ZV9pZCI6MzgxMjI5MDc5NTc1OTQ2fQ==

    body = BeautifulSoup(r.text, "lxml")
    print("[* All JS scripts]")
    # find all scripts one of them will be "accessToken"
    for script in body.find_all("script"):
        print(script)


if __name__ == "__main__":
    face_token()
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы