Python Requests模拟登录实现图书馆座位自动预约


Posted in Python onApril 27, 2018

本文实例为大家分享了Python实现图书馆座位自动预约的具体代码,供大家参考,具体内容如下

配置

通过公网主机定时运行脚本,并发送邮件到自己的qq邮箱,这样在微信就会有消息提示是否预约成功

vim /etc/crontab

设置每到早上7:01自动运行脚本即可

程序流程

(以yuyue.juneberry.cn网站为例)

  • get访问登录页面,获取cookie和表单里面的隐藏post字段
  • 构造登录post数据,加入从表单里面拿到的隐藏post字段
  • post构造后的数据,模拟登录,激活cookie(使cookie有登入权限)
  • get访问座位预约界面,激活cookie(使cookie有预约座位权限)
  • post预约请求,实现预约座位
  • 解析返回结果,判断是否成功,并邮件提醒

要点

  • requests库中的requests.session() 能够创建可传递cookies的会话
  • 拿到<input type=hidden>的数据并传递到post的数据中
  • 抓包判断网站逻辑,筛选出各个请求的参数,并在程序中实现

函数解释

  • class FUCK()主类
  • _get_date_str(self):获取当前日期,并加上一天,用这个函数构造url的特征字段(图书馆设置提前一天预约座位)
  • def _get_order_url(self):构造"预约座位"的post目标url
  • def _get_static_post_attr:这个函数解析get请求的返回页面,并从中提取出<input type=hidden>的字段,用于之后的构造post数据
  • def login(self):实现登录功能
  • def run(self):实现座位预约功能
  • def _is_success(self, text):判断预约结果
  • def error_log_once(self, text='default error (once)'):
  • def error_log(self, text='default error'):这两个函数设置程序状态为"已经出错"或者"未出错"状态(用于自动化运行的时候避免将重复的错误信息写入日志)
  • def error_log(self, text='default error'):单次将错误信息写入本地日志
  • sendmail.send_mail()邮件发送模块

代码及注释

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

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

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

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

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


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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python之PyUnit单元测试实例
Oct 11 Python
Python在不同目录下导入模块的实现方法
Oct 27 Python
python实现读取excel写入mysql的小工具详解
Nov 20 Python
使用python 打开文件并做匹配处理的实例
Jan 02 Python
Python 实现子类获取父类的类成员方法
Jan 11 Python
python安装scipy的步骤解析
Sep 28 Python
解决Jupyter Notebook开始菜单栏Anaconda下消失的问题
Apr 13 Python
python rolling regression. 使用 Python 实现滚动回归操作
Jun 08 Python
python 安装移动复制第三方库操作
Jul 13 Python
小白教你PyCharm从下载到安装再到科学使用PyCharm2020最新激活码
Sep 25 Python
python 获取字典特定值对应的键的实现
Sep 29 Python
Python3读写ini配置文件的示例
Nov 06 Python
Python多线程中阻塞(join)与锁(Lock)使用误区解析
Apr 27 #Python
python队列queue模块详解
Apr 27 #Python
浅谈tensorflow1.0 池化层(pooling)和全连接层(dense)
Apr 27 #Python
python线程中同步锁详解
Apr 27 #Python
python数字图像处理之高级形态学处理
Apr 27 #Python
python线程池threadpool实现篇
Apr 27 #Python
python数字图像处理之骨架提取与分水岭算法
Apr 27 #Python
You might like
php.ini 中文版
2006/10/28 PHP
PHP写杨辉三角实例代码
2011/07/17 PHP
PHP中使用Session配合Javascript实现文件上传进度条功能
2014/10/15 PHP
php轻量级的性能分析工具xhprof的安装使用
2015/08/12 PHP
php微信公众平台开发之获取用户基本信息
2015/08/17 PHP
浅析PHP7的多进程及实例源码
2019/04/14 PHP
基于jQuery的前端数据通用验证库
2011/08/08 Javascript
javascript动画浅析
2012/08/30 Javascript
javascript异步编程代码书写规范Promise学习笔记
2015/02/11 Javascript
js判断请求的url是否可访问,支持跨域判断的实现方法
2016/09/17 Javascript
JavaScrpt判断一个数是否是质数的实例代码
2017/06/11 Javascript
浅谈JavaScript中的属性:如何遍历属性
2017/09/14 Javascript
解决Jstree 选中父节点时被禁用的子节点也会选中的问题
2017/12/27 Javascript
详解基于Node.js的HTTP/2 Server实践
2018/05/31 Javascript
json字符串传到前台input的方法
2018/08/06 Javascript
vue2.0移动端滑动事件vue-touch的实例代码
2018/11/27 Javascript
[43:57]Liquid vs Mineski 2019国际邀请赛小组赛 BO2 第二场 8.16
2019/08/19 DOTA
python将字符串转换成数组的方法
2015/04/29 Python
简单谈谈python中的多进程
2016/11/06 Python
python机器学习案例教程——K最近邻算法的实现
2017/12/28 Python
解决Python 爬虫URL中存在中文或特殊符号无法请求的问题
2018/05/11 Python
python Scrapy框架原理解析
2021/01/04 Python
css3动画事件—webkitAnimationEnd与计时器time事件
2013/01/31 HTML / CSS
HTML5 body设置自适应全屏
2020/05/07 HTML / CSS
廉价连衣裙和婚纱礼服在线销售:Tbdress
2019/02/28 全球购物
STRATHBERRY苏贝瑞包包官网:西班牙高级工匠手工打造
2020/11/10 全球购物
C#笔试题
2015/07/14 面试题
介绍一下write命令
2012/09/24 面试题
网络优化专员求职信
2014/05/04 职场文书
给校长的建议书500字
2014/05/15 职场文书
学校先进集体事迹材料
2014/05/31 职场文书
弘扬焦裕禄精神走群众路线思想汇报
2014/09/12 职场文书
师范生见习报告
2014/10/31 职场文书
2015年团委副书记工作总结
2015/07/23 职场文书
导游词之丽江普济寺
2019/10/22 职场文书
Github 使用python对copilot做些简单使用测试
2022/04/14 Python