0

To create cookies with selenium:

cookies.py

import time
import json

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait    
driver = webdriver.Chrome()
target =  "xxx.yyy"
driver.get(target)
time.sleep(60)
with open('cookies.txt','w') as cookief:
    cookief.write(json.dumps(driver.get_cookies()))    
driver.close()

I logined the website xxx.yyy manually and created cookies.txt file,now login with the script:

relogin.py

import json
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
target = "xxx.yyy"
driver.get(target)
driver.delete_all_cookies()
with open('cookies.txt','r') as cookief:
    cookieslist = json.load(cookief)
    for cookie in cookieslist:
        if 'expiry' in cookie:
            del cookie['expiry']
        driver.add_cookie(cookie)
driver.refresh()

The target website can relogin with python3 relogin.py,tomorrow i try again with python3 relogin.py,it failed,the cookies lasted for almost one day long.How to keep the cookie alive forever in Selenium scripts ?

cubick
  • 295
  • 3
  • 11
showkey
  • 449
  • 30
  • 101
  • 235

0 Answers0