Selenium: Get & Save Cookies Guide

To access and store cookies, you can utilize the get_cookies() method in Selenium to fetch all the current page’s cookies and store them in a variable. Afterwards, you can save these cookies to a file for later use in sessions.

Here is an example code using Python and Selenium to retrieve and save Cookies.

from selenium import webdriver

# 启动浏览器
driver = webdriver.Chrome()

# 访问网页
driver.get("https://www.example.com")

# 获取并打印当前页面的所有Cookies
cookies = driver.get_cookies()
for cookie in cookies:
    print(cookie)

# 保存Cookies到文件
with open("cookies.txt", "w") as f:
    for cookie in cookies:
        f.write(f"{cookie['name']}={cookie['value']}; ")

# 关闭浏览器
driver.quit()

In this example, we first launched the Chrome browser and accessed a webpage. Next, we used the get_cookies() method to retrieve all the Cookies from the current page and saved them in a variable. Then, we saved these Cookies to a text file in the format of name=value for each Cookie. Finally, we closed the browser.

You can use the add_cookie() method to add these cookies to the browser when you need to load them in future conversations. Here is an example code for loading cookies:

from selenium import webdriver

# 启动浏览器
driver = webdriver.Chrome()

# 访问网页
driver.get("https://www.example.com")

# 加载Cookies
with open("cookies.txt", "r") as f:
    cookies = f.read().strip().split("; ")
    for cookie in cookies:
        name, value = cookie.split("=")
        driver.add_cookie({'name': name, 'value': value})

# 重新刷新页面
driver.refresh()

# 关闭浏览器
driver.quit()

In this example, we first launch the Chrome browser and visit a webpage. We then load previously saved cookies from a file and add them to the browser using the add_cookie() method. Finally, we refresh the page to make the new cookies effective and close the browser.

I hope this helps you!

bannerAds