使用环境
- Python:3.9.1
- Selenium:4.0
- Chrome:94.0.4606.61
- Windows 10
操作步骤
-
获取账号cookie
-
手动打开页面登录后,再通过谷歌插件EditThisCookie来快速获取 -
EditThisCookie官网:https://www.editthiscookie.com/ -
EditThisCookie下载:https://download.csdn.net/download/qq_21238607/33237729 -
通过add_cookie()方法添加cookie代码示例 import time
from selenium import webdriver
url = 'https://mail.qq.com/'
cookies = "粘贴复制的网站cookie"
driver = webdriver.Chrome()
driver.get(url)
time.sleep(3)
for cookie in cookies:
driver.add_cookie(cookie)
time.sleep(3)
driver.refresh()
常见问题
-
问题报错:NameError: name ‘false’ is not defined 问题原因:通过EditThisCookie复制的Cookie内false、true均为小写,使用Python的话,需要修改为:False、True即可 解决办法:全量替换为:False、True即可
{
"domain": ".qq.com",
"hostOnly": false,
"httpOnly": false,
"name": "video_bucketid",
"path": "/",
"secure": false,
"session": true,
"storeId": "0",
"value": "4",
"id": 49
}
{
"domain": ".qq.com",
"hostOnly": False,
"httpOnly": False,
"name": "video_bucketid",
"path": "/",
"secure": False,
"session": True,
"storeId": "0",
"value": "4",
"id": 49
}
-
问题报错:assert cookie_dict[‘sameSite’] in [‘Strict’, ‘Lax’, ‘None’] AssertionError 问题原因:Cookie 的SameSite属性用来限制第三方 Cookie,从而减少安全风险,它可以这只三个值:‘Strict’, ‘Lax’, ‘None’,早期的Selenium版本也是不支持Cookie添加SameSite属性,如果添加,则会直接抛出异常,言归正传,我们可以通过查看复制的Cookie看出,QQ邮箱得到Cookie内的SameSite值为:unspecified,所以才会导致断言失败。 解决办法:1. 注释cookie内全部SameSite属性 2. 修改Cookie内全部SameSite属性值为:‘Strict’, ‘Lax’, 'None’即可
{
"domain": ".qq.com",
"hostOnly": False,
"httpOnly": False,
"name": "video_bucketid",
"path": "/",
"sameSite": "unspecified",
"secure": False,
"session": True,
"storeId": "0",
"value": "4",
"id": 49
}
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", "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})
参考链接
- Cookie 的 SameSite 属性:https://www.ruanyifeng.com/blog/2019/09/cookie-samesite.html
|