首頁 後端開發 Python教學 Python Requests模擬登入實現圖書館座位自動預約

Python Requests模擬登入實現圖書館座位自動預約

Apr 27, 2018 am 10:40 AM
python requests 實現

這篇文章主要為大家詳細介紹了Python Requests的模擬登錄,Python實現圖書館座位自動預約,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了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的會話

  • #拿到的資料並傳送到post的資料中

  • 抓包判斷網站邏輯,篩選出各個請求的參數,並在程式中實作

函數解釋

  • class FUCK()主類別

  • _get_date_str(self):取得目前日期,並加上一天,用這個函式建構url的特徵欄位(圖書館設定提前一天預約座位)

  • def _get_order_url(self):建構"預約座位"的post目標url

  • #def _get_static_post_attr:這個函數解析get請求的返回頁面,並從中提取出的字段,用於之後的構造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=&#39;hidden&#39;>的post参数,并添加到post_data中
  """
  soup = BeautifulSoup(page_content, "html.parser")
  for each in soup.find_all(&#39;input&#39;):
   if &#39;value&#39; in each.attrs and &#39;name&#39; in each.attrs:
    data_dict[each[&#39;name&#39;]] = each[&#39;value&#39;] # 添加到login的post_data中
    # self.data2[each[&#39;name&#39;]] = each[&#39;value&#39;] # 添加到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(&#39;http://yuyue.juneberry.cn/BookSeat/BookSeatListForm.aspx&#39;).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 &#39;<h5 id="MessageTip">已经存在有效的预约记录。</h5>&#39; in text:
   self.clear_error_once(&#39;[done!] You already ordered a seat!&#39;)
  elif &#39;<h5 id="MessageTip">选择的日期不允许预约。</h5>&#39; in text:
   self.clear_error_once(&#39;[done!] Date is wrong!&#39;)
  elif &#39;<h5 id="MessageTip">所选座位已经被预约。</h5>&#39; in text:
   self.clear_error_once(&#39;[done!] This seat is not available, maybe taken by others!&#39;)
  elif &#39;<h5 id="MessageTip">座位预约成功&#39; in text:
   self.clear_error_once(&#39;[done!] Success! An email is sending to you!&#39;)
   sendmail.send_mail(&#39;BJTU Library Seat_NO:&#39; + self.seatNO + &#39;ordered!&#39;,
        &#39;Sending by robot. Do not reply this mail!&#39;, self.mailto)
  else:
   self.error_log_once(&#39;Error! 302 to login page&#39;)

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

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

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

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


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

相關推薦:

python讀寫json檔案案例詳解(附程式碼)

#PYON正規表示式之re模組使用說明

#

以上是Python Requests模擬登入實現圖書館座位自動預約的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PHP和Python:解釋了不同的範例 PHP和Python:解釋了不同的範例 Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

在PHP和Python之間進行選擇:指南 在PHP和Python之間進行選擇:指南 Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

PHP和Python:深入了解他們的歷史 PHP和Python:深入了解他們的歷史 Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

vs code 可以在 Windows 8 中運行嗎 vs code 可以在 Windows 8 中運行嗎 Apr 15, 2025 pm 07:24 PM

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

visual studio code 可以用於 python 嗎 visual studio code 可以用於 python 嗎 Apr 15, 2025 pm 08:18 PM

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。

notepad 怎麼運行python notepad 怎麼運行python Apr 16, 2025 pm 07:33 PM

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。

sublime怎麼運行代碼python sublime怎麼運行代碼python Apr 16, 2025 am 08:48 AM

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

See all articles