search
HomeBackend DevelopmentPython TutorialPython 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=&#39;hidden&#39;>的post参数,并添加到post_data中
  """
  soup = BeautifulSoup(page_content, "html.parser")
  for each in soup.find_all(&#39;input&#39;):
   if &#39;value&#39; in each.attrs and &#39;name&#39; in each.attrs:
    data_dict[each[&#39;name&#39;]] = each[&#39;value&#39;] # 添加到login的post_data中
    # self.data2[each[&#39;name&#39;]] = each[&#39;value&#39;] # 添加到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(&#39;http://yuyue.juneberry.cn/BookSeat/BookSeatListForm.aspx&#39;).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 &#39;<h5 id="已经存在有效的预约记录">已经存在有效的预约记录。</h5>&#39; in text:
   self.clear_error_once(&#39;[done!] You already ordered a seat!&#39;)
  elif &#39;<h5 id="选择的日期不允许预约">选择的日期不允许预约。</h5>&#39; in text:
   self.clear_error_once(&#39;[done!] Date is wrong!&#39;)
  elif &#39;<h5 id="所选座位已经被预约">所选座位已经被预约。</h5>&#39; in text:
   self.clear_error_once(&#39;[done!] This seat is not available, maybe taken by others!&#39;)
  elif &#39;<h5 id="MessageTip">座位预约成功&#39; in text:
   self.clear_error_once(&#39;[done!] Success! An email is sending to you!&#39;)
   sendmail.send_mail(&#39;BJTU Library Seat_NO:&#39; + self.seatNO + &#39;ordered!&#39;,
        &#39;Sending by robot. Do not reply this mail!&#39;, self.mailto)
  else:
   self.error_log_once(&#39;Error! 302 to login page&#39;)

 def error_log_once(self, text=&#39;default error (once)&#39;):
  try:
   is_error_file = open(&#39;./isopen_xy.txt&#39;, &#39;r&#39;)
  except:
   is_error_file = open(&#39;./isopen_xy.txt&#39;, &#39;w&#39;)
  if &#39;1&#39; not in is_error_file.read():
   print &#39;writting error to log...&#39;
   self.error_log(text)
  else:
   print &#39;already written to log&#39;
  is_error_file.close()
  sendmail.send_mail(&#39;BJTU_Library system error once !&#39;, &#39;error text!&#39;)

 def error_log(self, text=&#39;default error&#39;):
  is_error_file = open(&#39;./isopen_xy.txt&#39;, &#39;w&#39;)
  is_error_file.write(&#39;1\n&#39;)
  is_error_file.close()

  f = open("./log_xy.txt", &#39;a&#39;)
  f.write(time.strftime("%Y-%m-%d %X", time.localtime()) + text + &#39;\n&#39;)
  f.close()

 def clear_error_once(self, text=&#39;success&#39;):
  print text
  is_error_file = open(&#39;./isopen_xy.txt&#39;, &#39;w&#39;)
  is_error_file.write(&#39;0\n&#39;)
  is_error_file.close()


if __name__ == &#39;__main__&#39;:
 if len(sys.argv) < 5:
  print &#39;Usage: python library.py [username] [password] [seat_NO] [email]&#39;
  print &#39;eg. python library.py S13280001 123456 003 XXXX@qq.com\n&#39;
  print &#39;Any problems, mail to: i[at]cdxy.me&#39;
  print &#39;#-*- Edit by cdxy 16.03.24 -*-&#39;
  sys.exit(0)
 else:
  FUCK(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])

Related recommendations:


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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.