python模拟用户登录
python模拟用户登录
一、授权认证
1、HTTP基础认证
import requests
from requests.auth import HTTPBasicAuth
url = "https://xxx.xxx.xxx/"
username = "admin"
password = "admin"
# HTTP基础认证
response = requests.get(url=url, auth=HTTPBasicAuth(username, password))
print(response.text)
2、利用urllib.request模块
import urllib.request
url = "https://xxx.xxx.xxx/"
username = "admin"
password = "admin"
# 创建一个密码管理器
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
# 添加进目标url,用户名,密码
password_mgr.add_password(None, url, username, password)
# 创建一个基本密码认证处理器并将密码管理器传递给他
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# 创建网络请求的构造器
opener = urllib.request.build_opener(handler)
response = opener.open(url)
print(response.read().decode("utf-8"))
二、Cookie认证
import requests
url = "https://xxx.xxx.xxx/"
username = "admin"
password = "admin"
# 创建会话对象
session = requests.Session()
# 构造登录请求的数据
login_data = {
"username": username,
"password": password
}
# 发送登录请求
response = session.post(url, data=login_data)
print(response.text)