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?
CodePudding user response:
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)
CodePudding user response:
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']