My goal is to log-in to Gmail, serialize the cookies, exit the browser, then open a new browser, load the saved cookies, and check my email without needing to enter my log-in details. Pretty straight-forward, and I've been able to do this with almost every website I've tried. However, Gmail forces me to sign in again, each time.
Here's my code:
from splinter import Browser
import selenium
import pickle
def export_cookies(browser, the_name):
yummy = browser.cookies.all(verbose=True)
location = 'cookies/' + the_name
pickle_save(yummy, location)
print(the_name, "saved", len(yummy))
def pickle_save(obj, location):
file_name = location
file_object = open(file_name, 'wb')
pickle.dump(obj, file_object)
file_object.close()
def pickle_load_account(cookie_file_name):
try:
return pickle.load(open(cookie_file_name, "rb"))
except FileNotFoundError:
return 0
def browser_add_cookies(browser, cookies):
if len(cookies) > 0:
for cookie in cookies:
browser.cookies.add({cookie['name']: cookie['value']})
print("-----", len(cookies), " cookies added, reloading")
browser.visit('https://mail.google.com/mail/u/0/#inbox')
else:
print("No cookies to load. Error.")
browser = Browser('firefox')
browser.visit('https://mail.google.com/mail/u/0/#inbox')
cookie_file = "cookies/name"
load_cookies = pickle_load_account(cookie_file)
browser_add_cookies(browser, load_cookies)
browser.visit('https://mail.google.com/mail/u/0/#inbox')
input("Save cookies?")
export_cookies(browser, "name")
This code assumes the cookies were already saved, but then re-saves them in the end, so a second run (if you sign in manually the first time).
My guess is that Gmail somehow uses a more advanced method of cookie recognition?
You are replicating cookies on for one domain. You need to replicate for below domains as well
accounts.google.com
mail.google.com
And may be even more, see the screenshot below on fresh login
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With