Use Python to implement the book expiration reminder, and use python to implement the book expiration reminder

Source: Internet
Author: User

Use Python to implement the book expiration reminder, and use python to implement the book expiration reminder

1. Simulate login to the Library Management System

Let's take a look at the login page (many schools have these management system pages that are very low ):

Two methods are used to simulate the login to the Library:

1. Construct a logon form to simulate Logon

This method of simulated login seems to be very reliable, but sometimes it is difficult to obtain the verification code. If a simple website, some will use the current time stamp to construct the verification code, this is easy to observe from the web page, but for example, the website we want to simulate login does not seem to be able to do this, because it uses the Math Function in the JavaScript standard library to directly generate a Random verification code link, you can observe the Code at the verification code from the following picture:

It usesMath.random()The function returns a pseudo-random number (greater than or equal to 0, less than 1) of the floating point value of [0-1)
Okay! Let's use a simpler way to simulate logon!

2. log on to the library through cookies

Cookie refers to the data (usually encrypted) stored on the user's local terminal by some websites to identify users and track sessions ).

Here we useRequestsLibrary to simulate the login process. Before that, we still have a question: how to obtain the Cookie ??
If you are using Google Chrome, you can press F12 to see the Cookie content. This is what you want:

Let's analyze the previous figure. I hope you can read it with patience:

Through the image, we know that we can get the borrow date and the expected return date. After obtaining the date, we can compare the expected return date with the current date to determine whether the expiration date is reached. Not to mention, paste the code first and then:

Import requestssession = requests. session () # The Session object allows you to maintain certain parameters across requests. It also maintains cookiesession among all requests sent by the same Session instance. headers = {'user-agent': 'mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/8080 ', 'cooker': 'asp. NET_SessionId = 1qri0rmoylpyrs45rurzme55; records = 1467535679,1469713840; records = 1469713840; PHPSESSID = ev339udv0rrhqg6tfdvfukqos1 '}

The above Code usesrequestsSession object to save the Cookie. If we need to jump to other pages, we do not need to simulate logon every time because the cookie has saved our logon status.

Will someone ask, isn't it about simulated login ?? Why not ??

In fact, the Cookie in the above Code has saved our login status, which is equivalent to having simulated logon. It is much easier to simulate logon, however, the disadvantage is that you need to manually enter the cookie on the logon page and paste it into the code from the logon page.

Ii. Obtain borrowed books

Through the analysis page, we can useBeautifulSoupTo extract what we need, what we need is the bar code, title and author of the book, the borrowing date, and the due date. In fact, we only need to pay back the date, however, for future use, obtain all the information of the book and save it to the database:

 

Defines a database operation functionTo facilitate future calls.

Def get_mysql (): conn = pymysql. connect (host = 'localhost', user = 'root', passwd = '000000', db = 'mysql', charset = 'utf8') # user indicates the database name, passwd is the password of the database. Generally, the character set must be defined as utf8. Otherwise, it is easy to encounter Encoding Problems When storing passwd in the database. cur = conn. cursor () # obtain the operation cursor cur.exe cute ('use Book') # use the book database return (cur, conn)

Define a function to obtain and save the book information:

Def get_book_name (book_url): html = session. get (book_url, cookies = cookie, headers = headers ). content. decode ('utf-8') soup = BeautifulSoup (html, 'lxml') book_bar = [] # the bar code list of books to determine whether the books to be stored in the database already exist in cur, conn = get_mysql () SQL = 'select * from book_list; 'cur.exe cute (SQL) rows = cur. fetchall () for row in rows: book_bar.append (row [1]) book_list = [] # This is used in the test, the function is to put the information list of each book in this list book_every = [] # A list of all information of a book. for book_time in soup. find_all ('td ', class _ = "whitetext"): print (book_time.get_text (). strip () # Remove the specified character (space by default) pattern = re. compile (r '\ s') content = re. sub (pattern, r'', book_time.get_text () # The purpose is to match and remove any blank characters. It seems that the removal of blank lines does not affect if content! = '': Book_every.append (content) if len (book_every) = 7: book_list.append (book_every) if book_every [0] not in book_bar: SQL = 'insert book_list (barcode, title and author, borrow date, due date, renewal volume, collection location, attachment) value ('+ "\'" \ + book_every [0] + "\', "+" \ '"+ book_every [1] +" \', "+" \ '"+ book_every [2] + "\', "+" \ '"\ + book_every [3] +" \', "+" \ '"+ book_every [4] + "\', "+" \ '"+ book_every [5] +" \', "+" \ '"\ + book_every [6] +" \' "+ '); 'try: cur.exe cute (SQL) conn. commit () commit T: conn. rollback () book_every = [] print (book_list)

Next, let's analyze the code without comments in the above Code. First, we add the processed informationbook_everyIn summary, we can see from the page source code (tp9.png) that only the first seven items are required in the information of a book, so we use a judgment statement:

If len (book_every) = 7: book_list.append (book_every) if book_every [0] not in book_title: SQL = 'insert book_list (barcode, title and author, borrowing date, due to the due date, renewal amount, collection location, attachment) value ('+ "\'" \ + book_every [0] + "\', "+" \ '"+ book_every [1] +" \', "+" \ '"+ book_every [2] + "\', "+" \ '"\ + book_every [3] +" \', "+" \ '"+ book_every [4] + "\', "+" \ '"+ book_every [5] +" \', "+" \ '"\ + book_every [6] +" \' "+ '); 'try: cur.exe cute (SQL) conn. commit () commit T: conn. rollback () # If the database fails to be stored, perform the rollback operation book_every = []

That is to say, if it is determined thatbook_everyIf there are already 7 items, the database is saved, andbook_everyReset to empty list

3. Send email reminders

First paste the Code:

Def send_message (): day_num = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31] day_num1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] SQL = 'select * from book_list; 'cur, conn = get_mysql () cur.exe cute (SQL) rows = cur. fetchall () local_time = time. strftime ("% Y-% m-% d", time. localtime () # obtain the current time local_time = str (local_time) times = re. split (r '-', local_time) year = times [0] number = 0 while (Tru E): for I in rows: print (I [4]) pattern = re. split (R'-', I [4]) if times [1] = pattern [1]: day = int (times [2]) -int (pattern [2]) if day> 0: print ('% d days expired' % day) number + = 1 send_email (day, number, I [2]) elif times [1]> pattern [1]: if (year % 4 = 0 and year % 100! = 0) or year % 400 = 0: extend_day = day_num1 [int (pattern [1])-1]-int (pattern [2]) + times [2] print ('% d days expired' % extend_day) number + = 1 send_email (day, number, I [2]) else: extend_day = day_num [int (pattern [1])-1]-int (pattern [2]) + times [2] print ('% d days expired' % extend_day) number + = 1 send_email (day, number, I [2]) else: print ('books not expired yet ') print (pattern [2]) time. sleep (3600*24)

Let's analyze the code. First, we can determine whether the expiration date is obtained based on the addition and subtraction of the current time and the expected date. Therefore, we consider the following:

1. if the date is the last month, we need to add or subtract the month, because the month of a leap year and a year is different, therefore, we define the day_num and day_num1 lists to indicate the number of days of the month in a year or year.

2. Then we use the month as the judgment condition to compare the days of the expiration period.

If the current month is equal to the expected month, perform the following operations. Note that the email sending function is already included. The email sending function will be posted below. You may think, why didn't I judge the year, because I generally borrowed books for a long time, so I didn't add this judgment

If times [1] = pattern [1]: day = int (times [2])-int (pattern [2]) if day> 0: print ('% d days expired' % day) number + = 1 send_email (day, number, I [2])

Then, when the current month is greater than the expected month, a leap year and a year are judged.

Elif times [1]> pattern [1]: if (year % 4 = 0 and year % 100! = 0) or year % 400 = 0: extend_day = day_num1 [int (pattern [1])-1]-int (pattern [2]) + times [2] print ('% d days expired' % extend_day) number + = 1 send_email (day, number, I [2])

The code for sending the email is as follows:

Def send_email (day, number, title ): from_addr = '2017 @ 163.com 'password =' won't tell you 'to_addr = '2017 @ qq.com 'smtp_server = 'smtp .163.com' text = 'hello, Guo weikuang, tell you a bad news. Please take your book and pay for it in the library! You have a book named "% s" that has expired '\' and has expired % d days. A total of % d books have expired !!! '% (Title, day, number) msg = MIMEText (text, 'plain', 'utf-8 ') msg ['from'] = format_addr ('library notification <% s> '% from_addr) msg ['to'] = format_addr ('administrator <% s>' % to_addr) msg ['subobject'] = Header ('greetings from Guo weikuang ...... ', 'utf-8 '). encode () server = smtplib. SMTP (smtp_server, 25) server. set_debuglevel (1) server. login (from_addr, password) server. sendmail (from_addr, [to_addr], msg. as_string () server. quit ()

Finally, send the email:

 

The above is the use of Python to implement all the content of book expiration reminders. This function is quite practical, and interested friends can practice it on their own. I hope it will help you learn Python.

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.