模拟用户登录网站

阿帅啊,长点心吧 / 2025-02-21 / 原文

模拟用户登录网站

requests模块
Requests 继承了urllib2的所有特性。Requests支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。

requests 的底层实现其实就是 urllib3

Requests的文档非常完备,中文文档也相当不错。Requests能完全满足当前网络的需求,支持Python 2.6—3.5,而且能在PyPy下完美运行。

支持get、post、put、delect等请求方式

安装方式

pip install requests

引用

import requests

模拟用户登录

#测试网址http://www.glidedsky.com/login

#调用标准库
import requests
import re

#登录信息
agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",

#请求头信息
header = {
    "user-Agent": str(agent),
    "Upgrade-Insecure-Requests": "1",
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4',
    "Referer": "http://www.glidedsky.com/",
  }

# 创建session保持回话连接
mf = requests.session()

#登录网址
post_url = 'http://www.glidedsky.com/login'

# 发送get请求获取登陆页面信息
cookie_dict = mf.get(post_url, headers=header).text

# 使用re解析登陆页面,得到token值
token = re.findall('<input type="hidden" name="_token" value="(.*?)">',cookie_dict)[0]

# 将token和账号密码封装成字典
post_data = {
    "email": "176xxx.com",
    "password": "mxxxx59",
    "_token": token,
}

#模拟用户登录2022-04-29 15:32:11 星期五
cookie = mf.post(post_url,data=post_data,headers=header)

#打印cookie信息(XSRF-TOKEN、glidedsky_session)
print(cookie.headers["Set-Cookie"])     #打印请求头的cookie信息
print(cookie.cookies.get("glidedsky_session"))      #获取指定的cookie信息
print(cookie.cookies.get_dict())        #以字典形式返回cookie所有信息
print(cookie.url)       #打url
print(cookie.request)       #打印请求方式

携带csrf-token
相关网站:https://cxybb.com/article/u014535666/106151119

上面使用破post模拟请求登录之后,后面可以直接使用mf去调用登录,不需要单独去获取登录cookie。request有会话保持。