一、查看浏览器cookie
cookie、session、token的区别:
- cookie存储在浏览器本地客户端,发送的请求携带cookie时可以实现登录操作。
- session存放在服务器。
- token应用于应用程序。
F12查看浏览器cookie:
二、cookie基本操作
1、获取cookie:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
url = "http://www.baidu.com/"
# 导入浏览器驱动
executable_path = 'chromedriver.exe'
service = Service(executable_path=executable_path)
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(20)
driver.get(url)
cur_cookies = driver.get_cookies() # 获取所有cookie
baidu_id_cookie = driver.get_cookie('BAIDUID') # 获取单个cookie
print(len(cur_cookies))
print(cur_cookies) # 输出cookie值
print(baidu_id_cookie)
driver.close()
运行结果如下:
2、获取特定cookie
cookie = driver.get_cookie('cookie_name')
3、删除单个cookie
driver.delete_cookie('cookie_name')
4、删除全部cookie
driver.delete_all_cookies()
5、添加某个cookie
(1)源码解释
def add_cookie(self, cookie_dict) -> None:
"""Adds a cookie to your current session.
:Args:
- cookie_dict: A dictionary object, with required keys - "name" and "value";
optional keys - "path", "domain", "secure", "httpOnly", "expiry", "sameSite"
:Usage:
::
driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure' : True})
driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'sameSite' : 'Strict'})
"""
if "sameSite" in cookie_dict:
assert cookie_dict["sameSite"] in ["Strict", "Lax", "None"]
self.execute(Command.ADD_COOKIE, {"cookie": cookie_dict})
else:
self.execute(Command.ADD_COOKIE, {"cookie": cookie_dict})
- 从中可以看出
add_cookie()
这个函数有一个参数cookie_dict
,它是以字典的形式传入的- 字典中必选的键是
"name"
和"value"
- 可选的键是
"path"
,"domin"
,"secure"
,"expiry"
,"httponly"
。
- 字典中必选的键是
(2)cookie中键名的含义
name cookie的名称
value cookie对应的值,动态生成的
domain 服务器域名
expiry Cookie有效终止日期
path Path属性定义了Web服务器上哪些路径下的页面可获取服务器设置的Cookie
httpOnly 防脚本攻击
secure 在Cookie中标记该变量,表明浏览器和服务器之间的通信协议为加密认证协议。
(3)添加cookie语法
cookie = {'name': 'cookie_name', 'value': 'cookie_value'}
driver.add_cookie(cookie)
6、完整示例
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
# 添加cookie
cookie = {'name': 'my_cookie', 'value': '12345'}
driver.add_cookie(cookie)
# 获取所有cookies
cookies = driver.get_cookies()
print(cookies)
# 删除特定cookie
driver.delete_cookie('my_cookie')
# 删除所有cookies
driver.delete_all_cookies()
driver.quit()
三、注意事项
添加cookie前,需要首先加载网站,这样Selenium才能知道cookie属于哪个网站
错误示例:
from selenium import webdriver
driver = webdriver.Chrome()
cookies = {"value": "value", "name": "name"}
driver.add_cookie(cookie_dict=cookies)
driver.get("https://www.ketangpai.com/M
正确示例:
from selenium import webdriver
driver = webdriver.Chrome()
cookies = {"value": "value", "name": "name"}
driver.get("https://www.ketangpai.com/User/login.html")
driver.add_cookie(cookie_dict=cookies)
driver.get("https://www.ketangpai.com/Main/index.html")
标签:cookies,12,name,selenium,driver,value,add,Cookie,cookie
From: https://www.cnblogs.com/xiao01/p/18115636