python selenium 保存cookie 读取cookie

日常笔记
回复
adm1n
Site Admin
帖子: 143
注册时间: 周六 6月 28, 2014 10:03 pm

python selenium 保存cookie 读取cookie

帖子 adm1n »

1. 保存cookie到文件中

代码: 全选

def save_cookies(browser, cookies_file_name="cookies.json"):
    print("正在保存Cookies到文件")
    cookies = browser.get_cookies()
    jsonCookies = json.dumps(cookies)
    with open(cookies_file_name, 'w') as cookies_file:
        cookies_file.write(jsonCookies)

2.从文件中读取cookie

代码: 全选

def get_cookies(browser, target_url, cookies_file_name="cookies.json"):

    print("正在从文件读取Cookies")
    browser.get(target_url)
    browser.delete_all_cookies()

    with open('cookies.json', 'r', encoding='utf-8') as f:
        listCookies = json.loads(f.read())
    for cookie in listCookies:
        browser.add_cookie({
            'domain': cookie['domain'],
            'name': cookie['name'],
            'value': cookie['value'],
            'path': '/',
            'expires': None
        })
    browser.get(target_url)
    return browser
参考资料:https://blog.csdn.net/fox64194167/artic ... s/80542717
回复