[Python] Selenium儲存/讀取cookies

儲存Cookies

import json

def save_cookies(browser):
    my_cookies = browser.get_cookies()
    f1 = open('cookies.txt', 'w')
    f1.write(json.dumps(g_cookies))

讀取Cookies

import json

def read_cookies(url):
    if os.path.exists('cookies.txt'):
        f = open('cookies.txt')
        browser.delete_all_cookies()
        my_cookies = f.read()
        my_cookies = json.loads(g_cookies)
        browser.get(self.url) #send one request to the target url before load saved cookies.
        if my_cookies is not None:
            for c in my_cookies:
                if 'expiry' in c:
                    del c['expiry'] #delete the expiry otherwise it may fail to load cookies
                browser.add_cookie(c)
            browser.get(self.url)