Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookies don't work when using Selenium

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?

like image 281
Winnie-c Avatar asked Feb 04 '26 16:02

Winnie-c


1 Answers

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")
like image 99
SteroidKing666 Avatar answered Feb 06 '26 07:02

SteroidKing666



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!