博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Python]-使用Requests模拟登录
阅读量:2056 次
发布时间:2019-04-28

本文共 2125 字,大约阅读时间需要 7 分钟。

文章目录

在《》中介绍了requests库的常用方法,本章介绍如何使用request进行用户登录。

登录说明

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

              Spring Security Example                  
Invalid username and password.
You have been logged out.

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 requestsimport requests.utilsimport http.cookiejar as cookiejarsession = 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

转载地址:http://fzilf.baihongyu.com/

你可能感兴趣的文章
leetcode 热题 Hot 100-3. 合并两个有序链表
查看>>
leetcode 热题 Hot 100-4. 对称二叉树
查看>>
Leetcode C++《热题 Hot 100-12》226.翻转二叉树
查看>>
Leetcode C++《热题 Hot 100-13》234.回文链表
查看>>
Leetcode C++《热题 Hot 100-14》283.移动零
查看>>
Leetcode C++《热题 Hot 100-15》437.路径总和III
查看>>
Leetcode C++《热题 Hot 100-16》448.找到所有数组中消失的数字
查看>>
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-27》17.电话号码的字母组合
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-30》31.下一个排列
查看>>
Leetcode C++《热题 Hot 100-40》64.最小路径和
查看>>