Python模拟登录

基于session和cookies

代码

import requests
from urllib.parse import urljoin
# 定义基础 URL 和登录、首页 URL
BASE_URL = 'https://login2.scrape.center/'
LOGIN_URL = urljoin(BASE_URL, '/login')
INDEX_URL = urljoin(BASE_URL, '/page/1')
# 定义用户名和密码
USERNAME = 'admin'
PASSWORD = 'admin'
# 创建一个 session 对象
session = requests.Session()
# 发送登录请求,获取 cookies
response_login = session.post(LOGIN_URL, data={
    'username': USERNAME,
    'password': PASSWORD
}, allow_redirects=False)
cookies = response_login.cookies
print(cookies)
# 发送首页请求,带上登录后获取的 cookies
response_index = session.get(INDEX_URL)
print('Response Status', response_index.status_code)
print('Response URL', response_index.url)
"""
注释解释如下:
- 导入 requests 和 urljoin 模块
- 定义 BASE_URL、LOGIN_URL 和 INDEX_URL,分别为网站的基础 URL、登录 URL 和首页 URL
- 定义 USERNAME 和 PASSWORD,为登录所需的用户名和密码
- 创建一个 session 对象,用于保持登录状态
- 发送登录请求,使用 session.post() 方法,传入登录所需的参数,allow_redirects=False 表示不允许重定向,获取登录后的 cookies
- 打印出获取的 cookies
- 发送首页请求,使用 session.get() 方法,传入首页 URL,带上登录后获取的 cookies,获取首页的响应结果
- 打印出响应状态码和响应 URL
"""

输出结果

<RequestsCookieJar[<Cookie sessionid=yp3nnj1qn1ec1lw5ori2k2wgxyub0ngx for login2.scrape.center/>]>
Response Status 200
Response URL https://login2.scrape.center/page/1

基于 JWT

代码

import requests
from urllib.parse import urljoin
# 定义基础 URL 和登录、首页 URL
BASE_URL = 'https://login3.scrape.center/'
LOGIN_URL = urljoin(BASE_URL, '/api/login')
INDEX_URL = urljoin(BASE_URL, '/api/book')
# 定义用户名和密码
USERNAME = 'admin'
PASSWORD = 'admin'
# 发送登录请求
response_login = requests.post(LOGIN_URL, json={
    'username': USERNAME,
    'password': PASSWORD
})
# 获取登录响应数据
data = response_login.json()
print("Response JSON", data)
# 获取 JWT token
jwt = data.get('token')
print("JWT", jwt)
# 设置请求头
headers = {
    'Authorization': f'jwt {jwt}'
}
# 发送首页请求
response_index = requests.get(INDEX_URL, params={
    'limit': 18,
    'offset': 0
}, headers=headers)
# 输出响应状态码、URL 和数据
print('Response Status', response_index.status_code)
print('Response URL', response_index.url)
print('Response Data', response_index.json())

输出结果

Response JSON {'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjc4MTM0MjMyLCJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSIsIm9yaWdfaWF0IjoxNjc4MDkxMDMyfQ.jEPHO0wQav0ECaI8hX8yjy7HzmRho7qnuByoRMsiNTI'}
JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjc4MTM0MjMyLCJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSIsIm9yaWdfaWF0IjoxNjc4MDkxMDMyfQ.jEPHO0wQav0ECaI8hX8yjy7HzmRho7qnuByoRMsiNTI
Response Status 200
Response URL https://login3.scrape.center/api/book/?limit=18&offset=0
Response Data {'count': 9200, 'results': [{'id': '34473697', 'name': 'R数据科学实战:工具详解与案例分析', 'authors': ['刘健', '邬书豪'], 'cover': None, 'score': '8.9'}, {'id': '34790654', 'name': 'Greenplum:从大数据战略到实现', 'authors': ['冯雷', '姚延栋', '高小明', '杨瑜'], 'cover': None, 'score': '8.9'}, {'id': '30329536', 'name': '数据密集型应用系统设计', 'authors': ['Martin Kleppmann'], 'cover': 'https://img3.doubanio.com/view/subject/l/public/s29872642.jpg', 'score': '9.6'}, {'id': '17707842', 'name': None, 'authors': None, 'cover': None, 'score': None}, {'id': '27080632', 'name': 'Streaming Systems', 'authors': ['Tyler Akidau', 'Slava Chernyak', 'Reuven Lax'], 'cover': None, 'score': ' 8.9 '}, {'id': '1046276', 'name': '温暖和百感交集的旅程', 'authors': ['\n            余华', '余华作品系列'], 'cover': 'https://img1.doubanio.com/view/subject/l/public/s1120387.jpg', 'score': '8.1'}, {'id': '25862578', 'name': '解忧杂货店', 'authors': ['\n                [日]\n            东野圭吾', '新经典文化', '新经典文库·东野圭吾作品'], 'cover': 'https://img3.doubanio.com/view/subject/l/public/s27264181.jpg', 'score': '8.5'}, {'id': '10554308', 'name': '白夜行', 'authors': ['[日] 东野圭吾'], 'cover': 'https://img1.doubanio.com/view/subject/l/public/s24514468.jpg', 'score': '9.2'}, {'id': '4913064', 'name': '活着', 'authors': ['余华'], 'cover': 'https://img3.doubanio.com/view/subject/l/public/s29053580.jpg', 'score': '9.4'}, {'id': '6015822', 'name': '在细雨中呼喊', 'authors': ['\n            余华', '余华作品(2008版)'], 'cover': 'https://img3.doubanio.com/view/subject/l/public/s6309302.jpg', 'score': '8.5'}, {'id': '10594787', 'name': '霍乱时期的爱情', 'authors': ['[哥伦比亚] 加西亚·马尔克斯'], 'cover': 'https://img3.doubanio.com/view/subject/l/public/s11284102.jpg', 'score': '9.0'}, {'id': '27064488', 'name': '活着', 'authors': ['余华'], 'cover': 'https://img1.doubanio.com/view/subject/l/public/s29652928.jpg', 'score': '9.4'}, {'id': '33440205', 'name': '你当像鸟飞往你的山', 'authors': ['[美] 塔拉·韦斯特弗'], 'cover': 'https://img9.doubanio.com/view/subject/l/public/s33492346.jpg', 'score': '9.0'}, {'id': '6082808', 'name': '百年孤独', 'authors': ['\n                [哥伦比亚]\n            加西亚·马尔克斯', '新经典文化', '\n            范晔', '新经典文库:加西亚·马尔克斯作品'], 'cover': 'https://img9.doubanio.com/view/subject/l/public/s6384944.jpg', 'score': '9.2'}, {'id': '34672176', 'name': '呼吸', 'authors': ['[美] 特德·姜'], 'cover': 'https://img1.doubanio.com/view/subject/l/public/s33519539.jpg', 'score': '8.6'}, {'id': '1007305', 'name': '红楼梦', 'authors': ['[清] 曹雪芹 著', '高鹗 续'], 'cover': 'https://img1.doubanio.com/view/subject/l/public/s1070959.jpg', 'score': '9.6'}, {'id': '34434309', 'name': '82年生的金智英', 'authors': ['[韩]赵南柱'], 'cover': 'https://img1.doubanio.com/view/subject/l/public/s33463759.jpg', 'score': '7.9'}, {'id': '1200840', 'name': '平凡的世界(全三部)', 'authors': ['\n            路遥', '茅盾文学奖获奖作品全集'], 'cover': 'https://img3.doubanio.com/view/subject/l/public/s1144911.jpg', 'score': '9.0'}]}

posted @ 2023-03-06 14:13  淦丘比  阅读(19)  评论(0编辑  收藏  举报