python+Selenium自动化之免登录(cookie及token)

目录

cookie免登录

通过接口获取cookie

启用浏览器绕过登录

添加token


使用登录可以减去每次登录的重复操作,直接操作系统登录后的菜单页面,也可以减少安全验证登录,如图像验证登录的操作。注意:cookie和token都有有效期。

cookie免登录

直接从开发者工具中获取cookie进行添加,下图为网页中多个站点的cookie,挑选需要的进行添加即可。

python 复制代码
from selenium import webdriver
from selenium.webdriver.edge.options import Options

# 一般只需要name和value
cookie = {'name': 'ZY44', 'value': 'tLonhTkz50iHzxjhIsaaaafferr:C'}

options = Options()
# options.add_argument('--headless')
wd = webdriver.Edge(options=options)

wd.add_cookie(cookie_dict=cookie)

#for c in cookies:   # 如果是多个cookie要添加,cookies存储为列表是,使用循环添加
#   wd.add_cookie(c)

wd.refresh()  # 刷新页面

wd.get(URL)

wd.quit()

raise exception_class(message, screen, stacktrace)

selenium.common.exceptions.InvalidCookieDomainException: Message: invalid cookie domain

(Session info: MicrosoftEdge=126.0.2592.87)

如果有上面的报错,可在wd.add_cookie(cookie_dict=cookie) 前添加一行wd.get(URL),如下:

python 复制代码
wd.get(URL)
wd.add_cookie(cookie_dict=cookie)
wd.get(URL)

通过接口获取cookie

通过接口获取cookie数据后,在selenium添加cookie使用

python 复制代码
def get_cookies():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    }
    host = 'https://baike.baidu.com'
    req = requests.get(host, headers=headers)
    cookie_data = req.cookies.get_dict()
    cookies = []
    for key, value in cookie_data.items():
        cookies.append(dict(name=key, value=value))
    return cookies

启用浏览器绕过登录

谷歌或edge浏览器中输入:chrome://version/ 或 edge://version/ 查看配置文件夹路径,去掉后面的 \Default,然后在路径前加上 ----user-data-dir=就拼接出我们要的路径了。

python 复制代码
profile_directory = r'--user-data-dir=C:\Users\xxx\AppData\Local\Microsoft\Edge\User Data'
python 复制代码
# 这里使用模糊匹配,把edge开头的进程都杀掉
if platform.system() == "Windows":
    os.system("taskkill -im msedge* -f")
else:
    os.system("killall -9 msedge*")

user_data = r'C:\Users\xxx\AppData\Local\Microsoft\Edge\User Data'
profile_directory = rf'--user-data-dir={user_data}'

options = Options()
# options.add_argument('--headless')
options.add_argument(profile_directory)
wd = webdriver.Edge(options=options)

wd.maximize_window()
wd.get(URL)

wd.quit()

注意:这种方法在使用时需要关闭对应浏览器的程序,否则会报错,所以在执行前需要杀掉对应浏览器的进程。上面代码使用模糊匹配查询杀掉进程,下面是全匹配。

python 复制代码
returnCode=os.system('taskkill /F /iM chrome.exe')    # 谷歌
returnCode=os.system('taskkill /F /iM iexplore.exe')  # IE
returnCode=os.system('taskkill /F /iM firefox.exe')  # 火狐
returnCode=os.system('taskkill /F /iM msedge.exe')  # edge
assert returnCode==0 #判断浏览器进程是否杀完

添加token

python 复制代码
    token = "my_token"

    options = Options()
    options.add_argument('--headless')
    wd = webdriver.Edge(options=options)

    wd.execute_script("window.localStorage.setItem('token', '%s');" % token)  # 使用selenium执行js的操作添加token

    wd.maximize_window()
    wd.get(url)
    wd.quit()
相关推荐
IVEN_4 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang5 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮6 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling6 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮9 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽9 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers