zoukankan      html  css  js  c++  java
  • 保证图书馆借书不过期

    Author: wangxianglong Date: 2016/6/23 8:39:43

    背景

    我们图书馆其实书更新的挺快,各方面都还可以的,但是没有过期提醒的功能,导致我多次超期罚现,很不爽,是时候来个脚本搞定他了

    写脚本

    之前关注了学习的官方微信公众号,介个可以查询信息,好就从这里入手,在浏览器中打开开始分析网页的运行情况,来提取出API

    chrome浏览器F12->Network,其实分析这些API真的需要耐心,多试试。忘了截图了T_T

    看代码吧:

    #!/usr/bin/env python
    #coding: utf-8
    
    import urllib2
    import urllib
    import cookielib
    from ast import literal_eval
    from time import localtime
    import datetime
    import smtplib  
    from email.mime.text import MIMEText 
    
    url = "https://api.xiyoumobile.com/xiyoulibv2/user/login"						#登录API, 求求不要攻击我们学校API!!!	
    rent_url = "https://api.xiyoumobile.com/xiyoulibv2/user/rent"					#借书信息查询API
    user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"
    headers = {"User-Agent": user_agent, "Referer": "https://lib.xiyoumobile.com/" } #创建头部,以防有防盗链给拒了
    
    mailto_list = ["xxxxxx@qq.com"]        		 									#通知邮箱
    mail_host = "smtp.163.com"    
    mail_user = "xxxxxxxx@163.com"													#发件邮箱
    mail_pass = "xxxxxxx"                 											#发件邮箱密码
    
    
    def main():
        try:
            cookies = cookielib.CookieJar()
            request_data = urllib.urlencode({										#提交的数据, 方式居然是GET,呵呵
                    'username': 'student_ID',
                    'password': 'password'
            })	
            
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))		#创建opener
            request = urllib2.Request(url=url, data=request_data, headers=headers)		
            response = opener.open(request)
            
            rst = response.read().decode('utf-8')
            rst = literal_eval(rst.replace('true','True').replace('false','False'))		#得到sessionID和path路径,玩的小把戏吧
            status, detail = rst["Result"], rst["Detail"]								#返回来是status,和上面说的sessionID和path
            
            if status:
                data = urllib.urlencode({"session": detail})							#拿到sessionID就可以直接请求了
                request = urllib2.Request(rent_url, data)								
                response = urllib2.urlopen(request)
                rent_info = response.read().decode('utf-8')								#请求之后就会返回借书的信息,做些处理就OK了
                rent_info = literal_eval(rent_info.replace('true','True').replace('false','False'))
                status_rent, rent_detail = rent_info["Result"], rent_info["Detail"]
                
                if status_rent:
                    send_info = ''
                    now_time = localtime()
                    now_date = datetime.date(now_time.tm_year, now_time.tm_mon, now_time.tm_mday)
                    for book in rent_detail:
                        d = book['Date']
                        deadline = datetime.date(int(d[:4]), int(d[4:6]), int(d[6:]))
                        delta = (deadline - now_date).days
                        if delta <= 2:
                            send_info += book['Title']
                            if book['CanRenew']:
                                send_info += '  可以续借  '
                            else:
                                send_info += '  不可续借 '
                            if delta >= 0:
                                send_info += '  剩余:' + str(delta) + " 天"
                            else:
                                send_info += '  超期了'
                            send_info += '
    
    '
                    if send_info:
                        print send_info
                        send_mail(mailto_list, '图书馆借书信息', send_info)				#快超期就发邮件提示
                    else:
                        print "书都好着呢"
                else:
                    print "可能接口出问题了。。。"
            else:
                print "学号或者密码错误"
        except urllib2.URLError, e:
            if hasattr(e, "code"):
                print e.code
            if hasattr(e, "reason"):
                print e.reason
                
    def send_mail(to_list, sub, content):
        me = "图书馆借书信息"+"<"+mail_user+">"
        msg = MIMEText(content, _subtype='plain', _charset='utf-8')
        msg['Subject'] = sub
        msg['From'] = me
        msg['To'] = ";".join(to_list)
        try:
            server = smtplib.SMTP()
            server.connect(mail_host)
            server.login(mail_user, mail_pass)
            server.sendmail(me, to_list, msg.as_string())
            server.close()
            print "发送成功"
            return True
        except Exception, e:
            print str(e)
            print "发送失败"
            return False
    
    
    if __name__ == "__main__":
        main()
    

    计划执行

    首先我云主机没钱的,所以crontab没法用了,哎怎么办呢, 嗯Window计划任务貌似可以,试试。可以让脚本在联网的时候就检查一遍。

    1. 打开: window键-> 控制面板 -> 计划任务(搜索一下)
    2. 创建任务 -> 起个名 -> 定义触发器 -> 定义动作
    3. 看图说话

    在脚本执行的时候,有的会有黑窗口,类型交互界面一样,不要!

    起个名

    定义触发器,其中10000表示网络连接的事件ID

    定义脚本,注意程序默认执行的程序是python.exe

    在任务网络连接的时候,都记录事件

  • 相关阅读:
    png-8 和 png-24的区别
    css控制标题长度超出部分显示省略号
    php正则表达式
    10分钟了解JSON Web令牌(JWT)
    Python制作微信小助手
    优质网站、赚钱、教程、分享、网赚
    从Github上将laravel项目拉到新开发环境
    gitlab添加公钥
    Git 配置用户名、密码
    虚拟机Oracle VM VirtualBox linux系统如何访问windows共享文件夹
  • 原文地址:https://www.cnblogs.com/wxl-dede/p/5609380.html
Copyright © 2011-2022 走看看