Saving and Loading Cookies in Selenium WebDriver Using Python
Saving and loading cookies in Python's Selenium WebDriver is a convenient feature for maintaining authenticated sessions across multiple browser instances or executions.
The getCookies() function in Selenium WebDriver returns a list of Cookie objects representing the current cookies for the current domain. To save these cookies to a file, we can use Python's built-in pickle module.
To save the cookies to a .txt file:
import pickle import selenium.webdriver driver = selenium.webdriver.Firefox() driver.get("http://www.google.com") pickle.dump(driver.get_cookies(), open("cookies.txt", "wb"))
To load the cookies from the .txt file later:
import pickle import selenium.webdriver driver = selenium.webdriver.Firefox() driver.get("http://www.google.com") cookies = pickle.load(open("cookies.txt", "rb")) for cookie in cookies: driver.add_cookie(cookie)
By following these steps, you can easily save and load cookies in Selenium WebDriver, ensuring that your browser sessions can be authenticated and customized as needed.
The above is the detailed content of How Can I Save and Load Cookies in Selenium WebDriver using Python?. For more information, please follow other related articles on the PHP Chinese website!