Home > Backend Development > Python Tutorial > How Can I Save and Load Cookies Using Python and Selenium WebDriver?

How Can I Save and Load Cookies Using Python and Selenium WebDriver?

Patricia Arquette
Release: 2024-12-16 05:56:10
Original
868 people have browsed it

How Can I Save and Load Cookies Using Python and Selenium WebDriver?

Saving and Loading Cookies in Python Selenium WebDriver

Q: Can you save and load cookies using Python's Selenium WebDriver?

A: Yes, you can manipulate cookies in Selenium WebDriver to preserve and reuse session information. Here's how to do it using Python:

Saving Cookies:

First, import the necessary module and create a WebDriver instance:

import pickle
driver = selenium.webdriver.Firefox()
Copy after login

Navigate to the desired website and retrieve the current cookies as a Python object:

driver.get("https://www.example.com")
cookies = pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))
Copy after login

Loading Cookies:

To add the saved cookies back to the WebDriver instance, do the following:

driver.get("https://www.example.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)
Copy after login

By following these steps, you can effectively save and load cookies in Python Selenium WebDriver to manage website sessions and share credentials across different executions.

The above is the detailed content of How Can I Save and Load Cookies Using Python and Selenium WebDriver?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template