python selenium 保存和读取cookie


class LocalCookies(object):
    def __init__(self):
        self.cookies_file = 'cookies.json'  # cookies文件

    def save(self, cookies):  # 保存
        jsonCookies = json.dumps(cookies)
        with open(self.cookies_file, 'w') as f:
            f.write(jsonCookies)

    def load(self):  # 读取
        try:
            with open(self.cookies_file, 'r', encoding='utf-8') as f:
                listCookies = json.loads(f.read())
                return listCookies
        except BaseException as e:
            return None

url = '目标网站'
driver.get(url)  # 打开url地址
# driver.delete_all_cookies()
listCookies = LocalCookies().load()  # 读取本地cookies,并且添加到driver中
if listCookies:
    for cookie in listCookies:
        driver.add_cookie({
            'domain': cookie['domain'],
            'name': cookie['name'],
            'value': cookie['value'],
            'path': '/',
            'expires': None
        })
driver.get(url)  # 再次打开

LocalCookies().save(driver.get_cookies())  # 保存cookies



评论

支持上传图片(拖动图片或者截图粘贴)

0 评论