Reputation: 209
I tried to automatically log in with cookies. So I saved the cookies after I successfully logged in via my account. However, every time I try to read the file and add cookies to get the URL. It just directs me to that URL. The exit code will be 0.
I don't know why. Could you please help? Thanks.
Here is my code:
import time
from selenium import webdriver
import pickle
def save_cookies(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:
# del cookie['domain']
print(cookie)
driver.add_cookie(cookie)
browser = webdriver.Chrome()
url="https://mail.qq.com/"
path="D:\\download\\test.txt"
browser.get(url)
load_cookie(browser,path)
time.sleep(2)
browser.get(url)
print(browser.get_cookies)
The cookies will be like when I print the cookie from the cookies:
{'expiry': 2147385600, 'httpOnly': False, 'name': 'pgv_pvi', 'path': '/', 'secure': False, 'value': '82039xxx'}
{'expiry': 1536315518, 'httpOnly': False, 'name': 'ptui_loginuin', 'path': '/', 'secure': False, 'value': '[email protected]'}
{'httpOnly': False, 'name': 'pgv_si', 'path': '/', 'secure': False, 'value': 's6206319xxx'}
{'httpOnly': False, 'name': 'ptisp', 'path': '/', 'secure': False, 'value': 'cm'}
I tried to print the cookies at the end of the code, but it seems it can't be added. Why? Did I miss anything?
Upvotes: 3
Views: 5004
Reputation: 573
Use chrome options user-data-dir for this. The cookies are always stored and can be used from there. This method is faster than doing by code.
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.protonmail.com")
Upvotes: 5