Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 739
L'ultimo Avatar asked Jul 31 '17 13:07

L'ultimo


1 Answers

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)
like image 77
Arount Avatar answered Oct 15 '22 02:10

Arount