It is possible to import cookies that were exported earlier in Python with Selenium using the add_cookie
function. The syntax for adding a cookie is as follows:
driver.add_cookie({'name': 'cookie_name', 'value': 'cookie_value', 'domain': 'cookie_domain'})
To import cookies from a file, you need to read the file and then use the json.loads
function to convert the JSON string into a Python dictionary. You can then loop through the dictionary and add each cookie using add_cookie
.
Here's an example of how you can import cookies from a file:
import json
from selenium import webdriver
driver = webdriver.Chrome()
# Read cookies from file
with open('cookies.json', 'r') as file:
cookies = json.loads(file.read())
# Add each cookie to the driver
for cookie in cookies:
driver.add_cookie(cookie)
# Visit a page to use the imported cookies
driver.get('https://www.example.com')
Asked: 2023-07-04 00:08:35 +0000
Seen: 11 times
Last updated: Jul 04 '23