用python實現12306搶票
阿新 • • 發佈:2018-12-24
用splinter或者selenium都可以實現。這兩個庫是實現web瀏覽器自動操作的庫。就是模擬人的點選等等一系列操作。
不過先對應你的谷歌瀏覽器版本下好對應的chromedriver,然後新增好環境變數
驗證碼的部分沒有做,就是在你登入的時候要手動點選驗證,但是登入進去之後就不用管了,買到票之後會播放歌曲提醒付款。
網頁的按鈕等的id直接登入頁面按F12開發者工具進行檢視。
城市的cookies也是通過此方法獲得。如上圖所示。
# -*- coding: utf-8 -*- from splinter.browser import Browser from time import sleep import time import pygame from selenium.webdriver.support.select import Select from selenium import webdriver from selenium.webdriver.support.select import Select class ticket(object): # 使用者名稱,密碼 username = u"使用者名稱" passwd = u"密碼" # 車次,選擇第幾趟,0則從上之下依次點選 order = 0 ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init" login_url = "https://kyfw.12306.cn/otn/login/init" initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" buy = "https://kyfw.12306.cn/otn/confirmPassenger/initDc" def login(self): self.driver.get(self.login_url) # 填充密碼 self.driver.find_element_by_name("loginUserDTO.user_name").send_keys(self.username) self.driver.find_element_by_name("userDTO.password").send_keys(self.passwd) print(u"等待驗證碼,自行輸入...") print("開始登入") sleep(5) while True: if self.driver.current_url!= self.initmy_url: sleep(1) else: break print("結束登入") def start(self): self.driver = webdriver.Chrome() self.login() sleep(3) self.driver.get(self.ticket_url) try: print(u"購票頁面開始...") self.driver.find_element_by_id("fromStationText").send_keys("長沙") self.driver.find_element_by_id("toStationText").send_keys("石門北") self.driver.find_element_by_id("train_date").send_keys("2018-03-28") # K-快速 Z-直達 D-動車 GC-高鐵/城際 T-特快 count = 0 if self.order != 0: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查詢").click() count += 1 print(u"點選查詢... 第 %s 次" % count) sleep(0.8) try: self.driver.find_by_text(u"預訂")[self.order - 1].click() except Exception as e: print(e) print(u"預訂。。。") continue else: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查詢").click() count += 1 print(u"點選查詢... 第 %s 次" % count) sleep(0.8) try: for i in self.driver.find_by_text(u"預訂"): i.click() sleep(1) except Exception as e: print(e) print(u"預訂 。。。") continue print(u"開始預訂...") sleep(3) sleep(1) print(u"開始選擇使用者...") self.driver.find_by_text(u"熊桐").last.click() print(u"提交訂單...") sleep(1) time.sleep(60) self.driver.find_by_id('submitOrder_id').click() sleep(1.5) self.driver.find_by_id('qr_submit_id').click() pygame.mixer.init() print("訂單完成,播放音樂提醒") track = pygame.mixer.music.load(file) pygame.mixer.music.play() time.sleep(60) pygame.mixer.music.stop() except Exception as e: print(e) cities = { '北京': '%u5317%u4EAC%2CBJP', '廣州': '%u5E7F%u5DDE%2CGZQ', '杭州': '%u676D%u5DDE%2CHZH', '深圳': '%u6DF1%u5733%2CSZQ', '武漢': '%u6B66%u6C49%2CWHN', '上海': '%u4E0A%u6D77%2CSHH', '長沙': '%u957F%u6C99%2CCSQ', '石門北': '%u77F3%u95E8%u53BF%u5317%2CVFQ'} if __name__ == '__main__': file = r'.\PycharmProjects\untitled3\她說.mp3' ticket = ticket() ticket.starts = cities["長沙"] ticket.ends = cities["石門北"] ticket.dtime = "2018-03-28" ticket.start()