This article mainly for you in detail the Python requests simulation login, Python to realize the library seat automatic reservation, with a certain reference value, interested in small partners can refer to
The example of this article for everyone to share the Python implementation of the library seat automatic booking code for your reference, the specific content as follows
Configuration
Run the script through the public network host, and send mail to their QQ mailbox, so there will be a message to indicate whether the appointment is successful
Vim/etc/crontab
Set the script to run automatically every 7:01
Program Flow
(Take yuyue.juneberry.cn website as an example)
Get access to the login page for hidden post fields in cookies and forms
Constructs the login post data, joins the hidden post field which gets from the form inside
Post-constructed data, impersonate login, activate cookie (allow cookies to have login privileges)
Get access to the seat reservation interface to activate cookies (so that cookies have reserved seat privileges)
Post Reservation request for seat reservation
Parse returns results, determine success, and email alerts
Points
requests.session () in the requests library can create a session that delivers cookies
Get the <input type=hidden> data and pass it to the post data.
Grab the packet to judge the site logic, filter out the parameters of each request, and implement in the program
function explanation
Class fuck () main class
_get_date_str (self): Gets the current date, plus one day, use this function to construct a feature field for the URL (library set up a day in advance to reserve a seat)
def _get_order_url (self): constructs the post destination URL for "Reservation seat"
def _get_static_post_attr: This function parses the return page of a GET request and extracts the field from the <input type=hidden> for subsequent construction of the post data
def login (self): Implement login function
def run (self): Enable seat reservation function
def _is_success (self, text): Judging the appointment result
def error_log_once (self, text= ' default error (once) '):
def error_log (self, text= ' default error '): These two functions set the program status to "already faulted" or "not in error" state (to avoid writing duplicate error messages to the log when automating the operation)
def error_log (self, text= ' default error '): write error message to local log one time
sendmail.send_mail () Mail Sending module
Code and comments
#/bin/python#-*-coding:utf-8-*-import timeimport sysimport requestsfrom BS4 import beautifulsoupfrom Mail Import sendm ail__author__ = ' XY ' # Main class class Fuck (): def __init__ (self, username, password, seatno, mailto): "" "initialized with four parameters, username, password, seat number to reserve , email "" "Self.username = Username Self.password = Password Self.seatno = Seatno Self.mailto = mailto self.b Ase_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 () # Creating transitive Cook IES Session # Post data for login Self.data1 = {' subcmd ': ' Login ', ' Txt_loginid ': self.username, # s+ ' Txt_password ' : Self.password, # password ' selschool ': 60, # 60 means Beijing Jiaotong University} # Post data for order a seat self.data2 = {' subcmd ': ' Query ' ,} # Custom HTTP header, however I did not use self.headers in the program = {' Connection ': ' keep-alive ', ' content-type ': ' Application/x-www-form-ur Lencoded ',} self.login () Self.run () self._is_success (self.final_content) # When a program error is canceled, uncomment the line to print some parameters # 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 ', '%2f 4%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 ') \. Re Place ('%2f10%2f32 ', '%2f11%2f1 ') \. Replace ('%2f11%2f31 ', '%2f12%2f1 ') \. Replace ('%2f12%2f32 ', '%2f1%2f1 ') return da Te_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): "" "Get the Post parameter of <input type= ' hidden ' > and add it to Post_data" "" Soup = BeautifulSoup (page_content, "Html.parser Soup.find_all (' input '): If ' value ' in Each.attrs and ' name ' in each.attrs:data_dict[each[' name ']] = each[' value '] # added to login's Post_data # self.data2[each[' name ']] = each[' value '] # added to 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 # p Rint 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): # This get means: The original cookie does not have an appointment permission, # After accessing this get, the CO Okie has the appointment permission to perform the next post self.middle_content = Self.s.get (' http://yuyue.juneberry.cn/BookSeat/BookSeatListForm.aspx '). Content # After testing, this post requires only one subcmd parameterCan return normally, so you do not have to update the post parameters based on Get content # self.data2 = self._get_static_post_attr (Middle_content, SELF.DATA2) # This post request completes the appointment function! R = Self.s.post (Self.order_url, self.data2) self.final_content = R.content def _is_success (self, text): "" "accepts the final HTML content , determine if the success is successful, and trigger logging and MailTips "" "If '