Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to Save and Re-load Gmail Cookies with Selenium/Splinter

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?

like image 889
jonbon Avatar asked Nov 07 '22 07:11

jonbon


1 Answers

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

Domains

like image 154
Tarun Lalwani Avatar answered Nov 14 '22 20:11

Tarun Lalwani