Python: use cookie to login with Selenium

What I want to do is to open a page (for example youtube) and be automatically logged in, like when I manually open it in the browser.

From what I've understood, I have to use cookies, the problem is that I can't understand how.

I tried to download youtube cookies with this:

driver = webdriver.Firefox(executable_path="driver/geckodriver.exe")
driver.get("https://www.youtube.com/")
print(driver.get_cookies())

And what I get is:

{'name': 'VISITOR_INFO1_LIVE', 'value': 'EDkAwwhbDKQ', 'path': '/', 'domain': '.youtube.com', 'expiry': None, 'secure': False, 'httpOnly': True}

So what cookie do I have to load to automatically log in?


Solution 1:

You can use pickle to save cookies as text file and load it later:

def save_cookie(driver, path):
    with open(path, 'wb') as filehandler:
        pickle.dump(driver.get_cookies(), filehandler)

def load_cookie(driver, path):
     with open(path, 'rb') as cookiesfile:
         cookies = pickle.load(cookiesfile)
         for cookie in cookies:
             driver.add_cookie(cookie)

Solution 2:

I would advise in using json format, because the cookies are inherently dictionaries and lists. Otherwise this is the approved answer.

import json

def save_cookie(driver, path):
    with open(path, 'w') as filehandler:
        json.dump(driver.get_cookies(), filehandler)

def load_cookie(driver, path):
    with open(path, 'r') as cookiesfile:
        cookies = json.load(cookiesfile)
    for cookie in cookies:
        driver.add_cookie(cookie)