1.首先我们先来了解下cookie的几种方法
get_cookies():获取所有cookie值
get_cookie(name):根据cookie的name值获取对应的value值
get_all_cookies:删除所有cookie
get_delete_cookie(name):根据name值删除对应的value值
add_cookie(dict):添加cookie值,类型为字典
2.实例
1)进入百度登录页面,等待30s,手动输入账号和密码点击登录
option = webdriver.ChromeOptions() option.add_experimental_option("excludeSwitches", ["enable-automation"]) driver = webdriver.Chrome(options=option) driver.get("https://www.baidu.com/") time.sleep(30)
2)获取所有cookies值,并存储在本地json文件中
cookie_all = driver.get_cookies() with open("./file.json", mode="w") as f: json.dump(cookie_all, f)
3)读取本地cookie值并添加
with open("./file.json", mode="r") as b: list_cooke = json.load(b) # 读取cookie for cook in list_cooke: driver.add_cookie(cook) # for遍历添加cookie driver.refresh() # 刷新页面
3.完整代码
import json import time from selenium import webdriver def option(): options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["enable-automation"]) driver = webdriver.Chrome(options=options) driver.get("https://www.baidu.com/") time.sleep(30) return driver # 获取cookie值 cookie_all = option().get_cookies() with open("./file.json", mode="w") as f: json.dump(cookie_all, f) # 读取cookie值 with open("./file.json", mode="r") as b: list_cooke = json.load(b) # 读取cookie for cook in list_cooke: option().add_cookie(cook) # for遍历添加cookie option().refresh() # 刷新页面
标签:cookies,网页,option,get,driver,selenium,json,cookie From: https://www.cnblogs.com/lihongtaoya/p/16630225.html