


Python Requests simulates login to realize automatic reservation of library seats
This article mainly introduces the simulated login of Python Requests in detail. Python realizes automatic reservation of library seats, which has certain reference value. Interested friends can refer to it.
The examples in this article are Everyone shared the specific code for automatic reservation of library seats in Python for your reference. The specific content is as follows
Configuration
Run the script regularly through the public network host and send it Send the email to your qq mailbox, so that there will be a message on WeChat to prompt whether the appointment is successful
vim /etc/crontab
Set up every morning at 7: 01 Run the script automatically
Program flow
(Take the yuyue.juneberry.cn website as an example)
get Visit the login page, obtain the cookie and the hidden post field in the form
Construct the login post data, and add the hidden post field obtained from the form
Post the constructed data, simulate login, activate cookie (so that cookie has login permission)
get access the seat reservation interface, activate cookie (so that cookie has permission to reserve seat)
Post reservation request to realize seat reservation
Analyze the return result, determine whether it is successful, and send an email reminder
Points
##requests.session() in the requests library Ability to create a session that can pass cookies
- Get the data of
and pass it to the post data
- Capture the packet to determine the website logic, Filter out the parameters of each request and implement them in the program
Function explanation
class FUCK()Main class
_get_date_str(self):Get the current date and add one day, use this function to construct the characteristic field of the url ( The library sets up a seat reservation one day in advance)
def _get_order_url(self):Construct the post target url of "reserve a seat"
def _get_static_post_attr:This function parses the return page of the get request and extracts the field for subsequent construction of post data
def login(self):Implement login function
def run(self):Implementation Seat reservation function
def _is_success(self, text):Judge the reservation result
def error_log_once( self, text='default error (once)'):
def error_log(self, text='default error'):These two The function sets the program status to "Error Already" or "No Error" (used to avoid writing repeated error messages to the log during automated running)
def error_log( self, text='default error'):Write error information to the local log once
sendmail.send_mail()Mail sending module
Code and comments
# /bin/python # -*- coding:utf-8 -*- import time import sys import requests from bs4 import BeautifulSoup from mail import sendmail __author__ = 'xy' # 主类 class FUCK(): def __init__(self, username, password, seatNO, mailto): """ 以四个参数初始化,用户名,密码,要预约的座位号,接受预约结果提醒邮件的邮箱 """ self.username = username self.password = password self.seatNO = seatNO self.mailto = mailto self.base_url = 'http://yuyue.juneberry.cn' self.login_url = 'http://yuyue.juneberry.cn' self.order_url = self._get_order_url() self.login_content = '' self.middle_content = '' self.final_content = '' self.s = requests.session() # 创建可传递cookies的会话 # post data for login self.data1 = { 'subCmd': 'Login', 'txt_LoginID': self.username, # S+学号 'txt_Password': self.password, # 密码 'selSchool': 60, # 60表示北京交通大学 } # post data for order a seat self.data2 = { 'subCmd': 'query', } # 自定义http头,然而我在程序里并没有使用 self.headers = { 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', } self.login() self.run() self._is_success(self.final_content) # 怀疑程序出错时,取消下行注释,可打印一些参数 # self._debug() def _get_date_str(self): s = time.localtime(time.time()) ########333 date_str = str(s.tm_year) + '%2f' + str(s.tm_mon) + '%2f' + str(s.tm_mday + 1) date_str = date_str.replace('%2f1%2f32', '%2f2%2f1') \ .replace('%2f2%2f29', '%2f3%2f1') \ .replace('%2f3%2f32', '%2f4%2f1') \ .replace('%2f4%2f31', '%2f5%2f1') \ .replace('%2f5%2f32', '%2f6%2f1') \ .replace('%2f6%2f31', '%2f7%2f1') \ .replace('%2f7%2f32', '%2f8%2f1') \ .replace('%2f8%2f32', '%2f9%2f1') \ .replace('%2f9%2f31', '%2f10%2f1') \ .replace('%2f10%2f32', '%2f11%2f1') \ .replace('%2f11%2f31', '%2f12%2f1') \ .replace('%2f12%2f32', '%2f1%2f1') return date_str def _get_order_url(self): return "http://yuyue.juneberry.cn/BookSeat/BookSeatMessage.aspx?seatNo=101001" + self.seatNO + "&seatShortNo=01" + self.seatNO + "&roomNo=101001&date=" + self._get_date_str() def _get_static_post_attr(self, page_content, data_dict): """ 拿到<input type='hidden'>的post参数,并添加到post_data中 """ soup = BeautifulSoup(page_content, "html.parser") for each in soup.find_all('input'): if 'value' in each.attrs and 'name' in each.attrs: data_dict[each['name']] = each['value'] # 添加到login的post_data中 # self.data2[each['name']] = each['value'] # 添加到order的post_data中 return data_dict def _debug(self): print self.order_url print self.data1 print self.data2 print self.headers print self.s.cookies # print self.login_content # print self.middle_content print self.final_content def login(self): homepage_content = self.s.get(self.base_url).content self.data1 = self._get_static_post_attr(homepage_content, self.data1) r = self.s.post(self.login_url, self.data1) self.login_content = r.content def run(self): # 这个get的意思是:原先的cookie没有预约权限, # 访问这个get之后,会使cookie拥有预约权限,从而执行下一个post self.middle_content = self.s.get('http://yuyue.juneberry.cn/BookSeat/BookSeatListForm.aspx').content # 经测试,这个post只需要一个subCmd的参数就可以正常返回,因此不必根据get内容更新post参数 # self.data2 = self._get_static_post_attr(middle_content, self.data2) # 这个post请求完成了预约功能! r = self.s.post(self.order_url, self.data2) self.final_content = r.content def _is_success(self, text): """ 接受最终的html内容,判断是否成功,并触发日志记录和邮件提醒 """ if '<h5 id="MessageTip">已经存在有效的预约记录。</h5>' in text: self.clear_error_once('[done!] You already ordered a seat!') elif '<h5 id="MessageTip">选择的日期不允许预约。</h5>' in text: self.clear_error_once('[done!] Date is wrong!') elif '<h5 id="MessageTip">所选座位已经被预约。</h5>' in text: self.clear_error_once('[done!] This seat is not available, maybe taken by others!') elif '<h5 id="MessageTip">座位预约成功' in text: self.clear_error_once('[done!] Success! An email is sending to you!') sendmail.send_mail('BJTU Library Seat_NO:' + self.seatNO + 'ordered!', 'Sending by robot. Do not reply this mail!', self.mailto) else: self.error_log_once('Error! 302 to login page') def error_log_once(self, text='default error (once)'): try: is_error_file = open('./isopen_xy.txt', 'r') except: is_error_file = open('./isopen_xy.txt', 'w') if '1' not in is_error_file.read(): print 'writting error to log...' self.error_log(text) else: print 'already written to log' is_error_file.close() sendmail.send_mail('BJTU_Library system error once !', 'error text!') def error_log(self, text='default error'): is_error_file = open('./isopen_xy.txt', 'w') is_error_file.write('1\n') is_error_file.close() f = open("./log_xy.txt", 'a') f.write(time.strftime("%Y-%m-%d %X", time.localtime()) + text + '\n') f.close() def clear_error_once(self, text='success'): print text is_error_file = open('./isopen_xy.txt', 'w') is_error_file.write('0\n') is_error_file.close() if __name__ == '__main__': if len(sys.argv) < 5: print 'Usage: python library.py [username] [password] [seat_NO] [email]' print 'eg. python library.py S13280001 123456 003 XXXX@qq.com\n' print 'Any problems, mail to: i[at]cdxy.me' print '#-*- Edit by cdxy 16.03.24 -*-' sys.exit(0) else: FUCK(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
Detailed explanation of python reading and writing json files (with code)
Instructions for using the re module of PYTHON regular expressions
The above is the detailed content of Python Requests simulates login to realize automatic reservation of library seats. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
