0

I have logged in to Facebook using selenium and saved cookies in a .pkl file but next time when I load cookies and refresh page, it won't log me in

Here is my code for login step:

import pickle
driver.get('https://facebook.com/')
pickle.dump(driver.get_cookies(), open(f"cookies.pkl", "wb"))

Load login info step:

cookies = pickle.load(open(f"cookies/{username}.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
driver.refresh()

And still I'm not logged in. Am I missing something?!

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

1 Answers1

0

To login within Facebook using cookies you need to follow a couple of steps as follows:

  • You should collect the cookies only after first time you have successfully logged in.

  • Moving ahead if you add the cookies and access the url you will be automatically logged in.

  • Sample codeblock:

    driver.get('https://facebook.com/')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#email"))).send_keys(email)
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#pass"))).send_keys(password +Keys.RETURN)
    pickle.dump(driver.get_cookies(),open("cookies.pkl","wb"))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[aria-label='Account Controls and Settings'] svg[aria-label='Your profile']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[contains(., 'Log Out')]"))).click()
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        driver.add_cookie(cookie)
    driver.get('https://facebook.com/')
    

References

You can find a couple of relevant detailed discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352