Python realizes the automatic reservation function of Library Seminar room

Source: Internet
Author: User
This article is mainly for you to introduce the Python implementation of the library automatic booking function, with a certain reference value, interested in small partners can refer to

This article for you to share the Python implementation of the library workshop automatic booking of the specific code for your reference, the specific content as follows

Brief introduction

Now many schools provide students with a very good learning environment, usually reflected in the self-study classroom facilities and equipment. What has to be mentioned is that our school library, with the construction of the new library, the museum also set up a number of functional areas, each layer is divided into a, B, C, D four areas, connected by the north-south corridor, the middle by the rotation staircase through one to five layers. Area A is a self-study area; B and C are the library of social sciences and natural sciences; District d is a special functional area, including film and television Hall, digital media maker Experience Center, wisdom training Classroom, cloud desktop electronic reading room and so on; B, C District East-west corridor with a size of 12 workshops;

The above paragraph I was copied from the library official on the internet, but really have to for the school library to order a praise. Return to the topic of this article, the school free for the vast number of teachers and students to provide a comfortable and well-equipped seminar room. However, these workshops are required to make an online appointment to be able to access the next day's appointment at 00:00, so it is "Midnight Oil" for a time-period (3-hour) workshop. Of course, the speed of hand in this process will have a huge advantage. If you have a good night's rest, you don't want to make an appointment to the seminar room. Just recently learned a little Python crawler, I intend to use the crawler to help me complete this arduous task. haha haha! (PS: Prevent malicious access, all links will not be released ha)

Python implementation Ideas

Think about the idea is quite simple, is nothing more than login account, find room, submit an appointment. Let's try it:

Login account

First open the login screen of our workshop appointment, the link is: U2fsdgvkx19ndfjkghn54msvy1zl7aucrur/ct0nz4orpi7ulksdsvufmgr0fgco
rn9z/f8h3bds9w==

OK, this first step login account is very test I this novice, but can not counseling. By referring to some other big guys using the method, is to open the Firefox firebug (ctrl+shift+e) To view the network situation, in this case a normal login.

You can see that we have a post here and then we can use the Requests.post method in Python.

In order to be able to log in successfully, to hide oneself is a reptile identity, in the message header, you can see our request header, as long as the parameters are copied over, compose their own headers = {...} To spoof the server.

Take a look at the parameters page, here the form data only three, respectively, corresponding to the verification code, account number and password. By copying the parameters here, we can make up our data = {...}. One of the needs of our attention is this verification code, whether it is artificial "self" can be identified, or automatic recognition of the machine, you need to save the verification code as a local file. In this way, there is a problem, every time you visit the server, the verification code will be transformed. Now let's take a good look at the idea, first we have to obtain a verification code and save it locally, which requires access to a server, and finally we have to submit our parameters to log in, and again to the server, this time the verification code and we obtained the verification code is not the same verification code. In the beginning of the attempt I can no longer log on to the server, that is, two times the verification code mismatch. How to achieve the first time to obtain the verification code and the verification code at the time of submission is consistent?

We need the same cookie here. In a few of the graphs above, we can see a cookie value. To ensure synchronization, we need to do this, and we have the same cookie value when we get the verification code and the cookie value when we submit the account password. So, in my program, the first step I made was to get a cookie value and then use that cookie value as a parameter in headers. The idea of login is like this, add a sentence, here the verification code I am manually identified by the >﹏<.

Find a Room

This step is actually a useless step, why there is this step, according to the custom of the appointment, we will produce how a step, but if the use of crawlers, as long as the successful login can directly submit the reservation form. Of course, if you want to make the automatic booking process more intelligent, you can add this step, you can see those rooms are also can be booked, here to customize the supplemental rules. I just skipped it.

Submit an Appointment

As with login, we also manually submit once, to see the network situation, you can use Python simulation of this process. Here I do not explain the stickers, the submission is also used Requests.post method. But one thing to note is that the headers here and the headers are not the same, so remind you, if in other similar appointment procedures can pay attention to see the different content post headers is consistent. I got a hole in here for a while.


#!/usr/bin/env python # _*_ coding:utf-8 _*_ # # @Version: 1.0 # @Time: 2018/4/10 # @Author: Circle Hydrocarbon # @File: reservation _4.py import requestsimport reimport jsonimport datetimeimport timedef get_cookies (): "" "Get Cookies" "" url = ' http://****   ' s = requests.session () s.get (URL) ck_dict = Requests.utils.dict_from_cookiejar (s.cookies) # convert jar format to Dict ck = ' jsessionid= ' + ck_dict[' Jsessionid '] # Recombinant cookies "" "Get QR Code" "Path = './code.png ' get_cookies_headers = {' User-anget ': ' mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) gecko/20100101 firefox/59.0 ', ' Cookie ': ck} get_cookies_url = ' http://************** ' Code_image = requests. Get (Get_cookies_url, Headers=get_cookies_headers) with open (path, ' WB ') as Fn:fn.write (code_image.content) Fn.clos E () print (' Verification code saved successfully ') return Ckdef login (cookies, hour, minute): Login_headers = {' Accept ': ' Text/html,application /xhtml+xml,application/xml;q=0.9,*/*;q=0.8 ', ' accept-encoding ': ' gzip, deflate ',   ' Accept-language ': ' zh-cn,zh;q=0.8,zh-tw;q=0.7,zh-hk;q=0.5,en-us;q=0.3,en;q=0.2 ', ' cache-control ': ' No-cache ', ' C Onnection ': ' keep-alive ', ' content-length ': ' A ', ' content-type ': ' application/x-www-form-urlencoded ', ' Cookie ': Cookies, ' Host ': ' ************** ', ' Pragma ': ' No-cache ', ' Referer ': ' http://************** ', ' upgrade-insecure ' -requests ': ' 1 ', ' user-agent ': ' mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) gecko/20100101 firefox/59.0 '} login_url = ' http://************** ' login_data = {' Codeimage ': input (' Please enter validation Code: '), ' uname ': ' ************** ', ' upass ': ' ************** '} requests.post (Login_url, Data=login_data, Headers=log in_headers) res = requests.get (' http://************** ', headers=login_headers) Reg_h = R ' <option value= (. *?) >\d{4}-\d{2}-\d{2} ' # matches available with an appointment hash Value_h = Re.findall (Reg_h, Res.text) "" "" "" "" "" "" "" "" counter = 0 while (True): Now = Datetime.datetime.now () # Gets current system time if now.hour = = Hour and Now.minute = =Minute:break Time.sleep (0.5) # Print (now) counter = counter + 1 if counter = = 240:res = REQUESTS.G ET (' http://************** ', headers=login_headers) Reg_h = R ' <option value= (. *?) >\d{4}-\d{2}-\d{2} ' # match can provide an appointment for hash reg_t = R ' (\d{4}-\d{2}-\d{2}) ' # match available date value_h = Re.findall (Reg_h, re S.text) value_t = Re.findall (reg_t, Res.text) with open ('./con_log.txt ', ' a ') as Fjs:fjs.write (eval (valu E_H[-1]) + ' +value_t[-1]+ ' +str (now) + ' \ n ') Fjs.close () print (' Save successful ') counter = 0 return str (eval (val UE_H[-1]) def reservation (Day_hash, cookies, Stime, etime): Reservation_data = {' _etime ': etime, # End time 11 o'clock, with a value of 11*60=6    ' _roomid ': ' 1285b3ca77594b3095c7b89d4922553c ', # Room ID ' _seatno ': ', ' _stime ': stime, # Start time 8 o'clock, its value is 8*60=480 ' _subject ': ' Learning ', # Seminar theme ' _summary ': ' Learning ', # Seminar outline ' ruleId ': Day_hash, ' UserCount ': 3, # Number of appointments ' users ': ' * * * * ', # Study number ' UUID ': ' ************** '} ReservatIon_headers = {' Accept ': ' Application/json, Text/javascript, */*; q=0.01 ', ' accept-encoding ': ' gzip, deflate ', ' Accept-language ': ' zh-cn,zh;q=0.8,zh-tw;q=0.7,zh-hk;q=0.5,en-us;q=0.3,en;q=0.2 ', ' cache-control ': ' No-cache ', ' Connection ': ' keep-alive ', ' content-length ': ' 239 ', ' content-type ': ' Application/json ', ' Cookie ': Cookies, ' Ho St ': ' ************** ', ' Pragma ': ' No-cache ', ' Referer ': ' http://************** ', ' user-agent ': ' Mozilla/5.0 (wind OWS NT 10.0; Win64; x64; rv:59.0) gecko/20100101 firefox/59.0 '} reservation_js = Json.dumps (reservation_data) Reservation_url = ' http://******* ' Status = Requests.post (Reservation_url, Data=reservation_js, headers=reservation_headers) # print (Stime, ETime) # print (status) print (Status.text) def main (): "" "Appointment policy one: 11:20-20.40" "" full_stime = [' 1060 ', ' 870 ', ' 680 '] full  _etime = [' 1240 ', ' 1050 ', ' 860 '] "" "" "" Reservation Strategy two: 10:00-13:00;13:50-16:50;17:40-20:40 "" "stime = [' 1060 ', ' 830 ', ' []] etime = [' 1240 ',' 1010 ', ' 780 '] cookies = get_cookies () Day_hash = login (cookies, 0, 0) # Set timing time for I in range (0, 3): Reservation ( Day_hash, cookies, stime[i], etime[i]) if __name__ = = ' __main__ ': Main ()

Achieve results

Ever since I learned Python, my mother never had to worry about me getting out of the seminar room. After adding a few lines of timed programs to the program, you can automatically make an appointment for the workshop at 00:00. Through the test found that the appointment to a large extent can be about the room, for example, 4-12, about three time period is 7 seconds, but in 4-13 actually spent 21 seconds, and make a time period by the other students to go. Of course, this program needs to be further improved to achieve the victory of "hand speed".

Fill in the last

There is not enough, welcome to exchange.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.