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

目录

cookie免登录

通过接口获取cookie

启用浏览器绕过登录

添加token


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

cookie免登录

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

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),如下:

wd.get(URL)
wd.add_cookie(cookie_dict=cookie)
wd.get(URL)

通过接口获取cookie

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

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=就拼接出我们要的路径了。

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

# 这里使用模糊匹配,把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()

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

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

    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()
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Django 中,可以使用 cookie 来实现用户登录。具体步骤如下: 1. 在 `views.py` 中编写用户登录的视图函数,示例代码如下: ```python from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) response = redirect('home') response.set_cookie('username', username) return response else: error_message = 'Invalid username or password' else: error_message = None return render(request, 'login.html', {'error_message': error_message}) ``` 2. 在 `login.html` 模板中添加登录表单,示例代码如下: ```html {% extends 'base.html' %} {% block content %} <h2>Login</h2> {% if error_message %} <p>{{ error_message }}</p> {% endif %} <form method="post"> {% csrf_token %} <label for="username">Username:</label> <input type="text" name="username" id="username"> <br> <label for="password">Password:</label> <input type="password" name="password" id="password"> <br> <button type="submit">Login</button> </form> {% endblock %} ``` 3. 在 `views.py` 中编写需要登录后才能访问的视图函数,示例代码如下: ```python from django.shortcuts import render from django.http import HttpResponse def home_view(request): username = request.COOKIES.get('username') if username: return render(request, 'home.html', {'username': username}) else: return HttpResponse('Please login first') ``` 4. 在 `urls.py` 中配置路由,示例代码如下: ```python from django.urls import path from . import views urlpatterns = [ path('login/', views.login_view, name='login'), path('', views.home_view, name='home'), ] ``` 以上就是使用 cookie 实现用户登录的简单示例。需要注意的是,在实际开发中,为了安全起见,应该对 cookie 进行加密和签名处理,以避免被恶意篡改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值