[Python]-使用Requests模拟登录

2023-05-16

文章目录

  • 登录说明
    • session操作
    • data序列化
  • 示例代码
    • 登录流程
    • 验证

在《使用Requests进行HTTP请求与文件上传下载》中介绍了requests库的常用方法,本章介绍如何使用request进行用户登录。

登录说明

一般页面登录都是使用Form实现的,以登录如下页面为例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
           xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
   <head>
           <title>Spring Security Example </title>
       </head>
   <body>
       <div th:if="${param.error}">
               Invalid username and password.
           </div>
       <div th:if="${param.logout}">
               You have been logged out.
           </div>
       <form th:action="@{/login}" method="post">
               <div><label> User Name : <input type="text" name="username"/> </label></div>
               <div><label> Password: <input type="password" name="password"/> </label></div>
               <div><input type="submit" value="Sign In"/></div>
        </form>
   </body>
</html>

session操作

一般页面登录后,都需要返回session(保存在cookies中)用于后续的验证,可通过LWPCookieJar方便地进行cookies的保存与加载。为例方便cookies操作,使用requests.session(),代替requests进行请求操作。

默认情况下,LWPCookieJar保存与加载时,会忽略掉discard与expired的项,为能正常的保存与加载,需要使用参数ignore_discard=True, ignore_expires=True

data序列化

请求参数中data会根据类型不同进行不同方式的序列化,在models.py的prepare_body中有对data的详细实现。

对于字典格式的data,会序列化为k1=v1&k2=v2格式,并在未设定content_type情况下,设定为application/x-www-form-urlencoded

示例代码

登录流程

在登录成功后,保存session到文件中,以便后续使用:

import requests
import requests.utils
import http.cookiejar as cookiejar

session = requests.session()
session.cookies = cookiejar.LWPCookieJar(filename='./security.cookie')

BaseUrl = 'http://127.0.0.1:7087/study/'

header = {
    'Referer': BaseUrl + "login",
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) Chrome/89.0.4389.82'
}


def login(user, psw):
    try:
        data = {
            'username': user,
            'password': psw,
        }

        resp = session.post(url=BaseUrl + 'login', headers=header, data=data)
        print(resp)
        if resp.status_code == requests.codes.ok:
            print('redirect url:', resp.url)
            cookie = requests.utils.dict_from_cookiejar(session.cookies)
            print(cookie)
            session.cookies.save(ignore_discard=True, ignore_expires=True)

            # if canRedirect(BaseUrl):
            #     print("Login success")

    except Exception as ex:
        print(ex)

验证

登录成功即使返回ok,也不一定是真的成果;最准确的方式是尝试登录一个需要验证的页面,若返回成功,则是真正的成功:

def canRedirect(url):
    try:
        # session.cookies.load(ignore_discard=True, ignore_expires=True)
        resp = session.get(url, headers=header)
        print(resp)
        return resp.status_code == requests.codes.ok
    except Exception as ex:
        print(ex)

    return False
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[Python]-使用Requests模拟登录 的相关文章

随机推荐

  • C++编译报错`XXX‘被多次定义总结;未定义的引用等等

    1 C 43 43 编译报错 96 XXX 被多次定义总结 报错原因 xff1a 诸如类似的报错都是因为可能在两个或者多个 cpp文件 h文件定义该全局变量 xff0c 属于重复定义问题 解决办法是 xff1a 在VScode全局搜索该变量
  • C++必备万能头文件“#include<bits/stdc++.h>”

    c 43 43 代码一个简单的头文件 xff1a span class token macro property span class token directive hash span span class token directive
  • Livox SLAM(带LIO+闭环检测优化)

    主题 xff1a Livox雷达LIO 43 闭环检测优化 开源地址 xff1a LiDAR SLAM 该开源为 Livox雷达实现了一个一体化且即用型的 LiDAR 惯性里程计系统 前端基于基于开源里程计框架LIO Livox获取里程计信
  • 大疆livox定制的格式CustomMsg格式转换pointcloud2

    官方livox driver驱动livox雷达发出的点云topic有两种 xff0c 一种是大疆览沃定制的格式CustomMsg格式 xff0c 另一种是将CustomMsg格式 转换过的pointcloud2格式 xff0c 参见 Liv
  • paddlepaddle

    项目用到了paddlespeech2 xff0c 学了几天paddlepaddle xff0c 简单记录一下 文章目录 1 手写数字识别任务2 极简方案构建手写数字识别模型模型设计训练配置训练过程模型测试 3 手写数字识别 之数据处理4 手
  • SC-Lego-LOAM解析(上)

    文章目录 正文imageProjectionfeatureAssociationFeature Extraction 正文 SC Lego LOAM实际上应该并不对应某一篇特定的论文 xff0c 而是韩国KAIST在github开源的代码
  • SC-Lego-LOAM解析(中)

    上回说到经过连续帧间匹配 xff0c 激光odo给出来一个位姿估计 xff0c 但是是存在不断的误差的积累的 xff0c 需要与绝对的参考 xff08 地图 xff09 进行匹配 xff0c 以及进行回环检测和全局位姿优化 这也是正是map
  • SC-Lego-LOAM解析(下)

    回环检测是一个相对独立的模块 xff0c 这里再开一篇专门说明 前面两篇已经说过 xff0c 先对点云做了预处理 xff0c 然后进行连续帧之间的匹配即激光odom xff0c 然后是scan to map匹配 xff0c 并保存关键帧的位
  • Blog文章导航

    文章超链接 为了更快速的找到感兴趣的文章 xff0c 把我之前写的blog做一个简单的归类 xff1a 一 Nuttx相关 关于Nuttx的开发环境搭建类的文章 xff1a 1 genromfs 的使用及nuttx下romfs制作 2 nu
  • 关于计算程序耗时的几个方法

    1 一个来自r3live的timer tool工具 xff1a 一个功能丰富的头文件 34 tools timer hpp 34 span class token macro property span class token direct
  • gitpush出现remote: Support for password authentication was removed on August 13, 2021.

    git push 报错 xff1a Username span class token keyword for span span class token string 39 https github com 39 span span cl
  • ubuntu解决github访问速度慢的一个小tip

    一 通过设置hosts来解决 xff1a 登录http tool chinaz com dns 查询以下域名映射 并分别取访问速度较快的一个ip xff0c 比如我的 github span class token punctuation
  • 搞SLAM装完一个新的ubuntu系统后需要的环境配置

    所有的文件上传百度云 xff1a 链接 https pan baidu com s 1xheyHxPwaD8Tb9QJ6SAHUA 提取码 gmt9 一个搞SLAM的小白 xff0c 新装完ubuntu系统后应该配置这些内容 1 换源2 安
  • 四元数、变换矩阵、欧拉角转换关系

    四元数to变换矩阵 Eigen span class token double colon punctuation span Quaterniond span class token function quaternion span spa
  • 队列queue最简单的复制拷贝方式

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • 影单:分享一下最近在看的一些电影

    1 千与千寻 电影讲的是少女千寻随爸爸妈妈搬去新的城市 xff0c 开车迷路 xff0c 进入了一个神秘隧道 xff0c 隧道另一边有个风情小镇 xff0c 爸爸妈妈没抵制得了食物的诱惑 xff0c 大吃特吃变成了猪 那是个妖怪的世界 xf
  • conda相关

    安装 ubuntu 18 04 安装conda环境 及 创建虚拟环境 创建虚拟环境 conda create span class token operator span n your env name python span class
  • 几种PCL点云显示方式

    注意添加头文件 xff1a span class token macro property span class token directive hash span span class token directive keyword in
  • 复盘一下slam中常用的几种点云类型

    使用livox雷达常涉及至少3种点云格式 xff0c 一个是livox官方定义的custom格式 xff0c 另外两个就是激光 视觉常用的pcl类型和ros类型 之前总结过Livox雷达驱动程序发布点云格式CustomMsg和pcl Poi
  • [Python]-使用Requests模拟登录

    文章目录 登录说明session操作data序列化 示例代码登录流程验证 在 使用Requests进行HTTP请求与文件上传下载 中介绍了requests库的常用方法 xff0c 本章介绍如何使用request进行用户登录 登录说明 一般页