I'm using selenium to access a page that requires logging in. Currently I'm doing something like this:
import json
from selenium.webdriver import Chrome
cookies_path = 'tmp/cookies.json'
cookies = json.load(open(cookies_path))
driver = Chrome()
driver.get('https://www.example.com/')
for cookie in cookies:
driver.add_cookie(cookie)
driver.get('https://www.example.com/user-data')
# do stuff
json.dump(driver.get_cookies(), open(cookies_path, 'w'))
driver.quit()
The script is scheduled to run every hour. However, it can only run successfully 23 times. At the 24th time, when driver.get('https://www.example.com/user-data')
is executed, the driver will be redirected to the login page and my code breaks. Then I have to manually log in again, manually save the cookies, but the new cookies will still be invalid after 24 hours. But on my own laptop, I can stay logged in on this website indefinitely and have never been redirected to log in. I tried skipping expired ones when adding cookies to the driver, but it did not help.
FYI the website is using OAuth2 and I guess my cookies expire when the session token expires on the server. Is there a way to keep the cookies valid indefinitely with selenium like with my browser?
Edit:
Just saw this person had the same problem as mine, but no answer so far.