0

I basically here the same question as here, only with Python.

I want to use Selenium to get the user to log in with a browser, then grab the session cookie that will contain the log in information, and finally close the browser. In an interactive session, it's easy to just wait until the authentication is complete before calling get_cookie(). But in run mode, I'm stuck.

From the Selenium documentation, I get that it is about defining a wait strategy. So I tried to repurpose their code example as follows:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get('https://examplecom/')
sessionId = WebDriverWait(driver, timeout=120).until(lambda d: d.get_cookie('session_cookie')['value'])

driver.quit()

Unfortunately, the following error is immediately raised:

TypeError: 'NoneType' object is not subscriptable

What should I do instead?

1
  • you know you can make a chrome profile and I think it will save any cookies in it Commented Aug 6, 2022 at 13:59

2 Answers 2

3

Duh! I was calling the value key as part of the wait function, thus even before it was available! This works:

sessionId = WebDriverWait(driver, timeout=120).until(lambda d: d.get_cookie('TK'))['value']
Sign up to request clarification or add additional context in comments.

Comments

0

To save cookies in Selenium, you can do as follows:

import os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

expanduser = os.path.expanduser('~')
options = webdriver.ChromeOptions()

and then add option of user-data-dir:

options.add_argument(f'--user-data-dir={expanduser}\\AppData\\Local\\Google\\Chrome\\any_Name_You_Want')

and then create your browser with these option:

browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)

4 Comments

That's not what I'm trying to do. All I want is to get the value of the session cookie. Running driver.get_cookie() after the browser login does what I want.
what do you need the session cookies for @mrgou
Why does it matter? I just need it for the rest of my program.
I don't know if this answer can help @mrgou

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.