程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python自動刷新12306搶票

編輯:Python
#!/usr/bin/env python
#-*- coding: utf-8 -*-
""" 通過splinter刷12306火車票 可以自動填充賬號密碼,同時,在登錄時,也可以修改賬號密碼 然後手動識別驗證碼,並登陸,接下來的事情,交由腳本來做了,靜靜的等待搶票結果就好(刷票過程中,浏覽器不可關閉) """
import re
from splinter.browser import Browser
from time import sleep
import time
import sys
import httplib2
from urllib import parse
import smtplib
import numpy as np
from email.mime.text import MIMEText
class BrushTicket(object):
"""買票類及實現方法"""
def __init__(self, user_name, password, passengers, from_time, from_station, to_station, number, seat_type):
"""定義實例屬性,初始化"""
# 1206賬號密碼
self.user_name = user_name
self.password = password
# 乘客姓名
self.passengers = passengers
# 起始站和終點站
self.from_station = from_station
self.to_station = to_station
# 乘車日期
self.from_time = from_time
# 車次編號
self.number = number.capitalize()
# 座位類型所在td位置
if seat_type == '商務座特等座':
seat_type_index = 1
seat_type_value = 9
elif seat_type == '一等座':
seat_type_index = 2
seat_type_value = 'M'
elif seat_type == '二等座':
seat_type_index = 3
seat_type_value = 0
elif seat_type == '高級軟臥':
seat_type_index = 4
seat_type_value = 6
elif seat_type == '軟臥':
seat_type_index = 5
seat_type_value = 4
elif seat_type == '動臥':
seat_type_index = 6
seat_type_value = 'F'
elif seat_type == '硬臥':
seat_type_index = 7
seat_type_value = 3
elif seat_type == '軟座':
seat_type_index = 8
seat_type_value = 2
elif seat_type == '硬座':
seat_type_index = 9
seat_type_value = 1
elif seat_type == '無座':
seat_type_index = 10
seat_type_value = 1
elif seat_type == '其他':
seat_type_index = 11
seat_type_value = 1
else:
seat_type_index = 7
seat_type_value = 3
self.seat_type_index = seat_type_index
self.seat_type_value = seat_type_value
# 主要頁面網址
self.login_url = 'https://kyfw.12306.cn/otn/login/init'
self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'
self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'
# 浏覽器驅動信息,驅動下載頁:https://sites.google.com/a/chromium.org/chromedriver/downloads
self.driver_name = 'chrome'
self.executable_path = r'H:\For personal use\PYTHON\file\chromedriver.exe'
def do_login(self):
"""登錄功能實現,手動識別驗證碼進行登錄"""
self.driver.visit(self.login_url)
sleep(1)
self.driver.fill('loginUserDTO.user_name', self.user_name)
self.driver.fill('userDTO.password', self.password)
print('請輸入驗證碼……')
while True:
if self.driver.url != self.init_my_url:
sleep(1)
else:
break
def start_brush(self):
"""買票功能實現"""
self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)
# 浏覽器窗口的大小
self.driver.driver.set_window_size(1000, 900)
self.do_login()
self.driver.visit(self.ticket_url)
try:
print('開始刷票……')
# 加載車票查詢信息
self.driver.cookies.add({
"_jc_save_fromStation": self.from_station})
self.driver.cookies.add({
"_jc_save_toStation": self.to_station})
self.driver.cookies.add({
"_jc_save_fromDate": self.from_time})
self.driver.reload()
count = 0
while self.driver.url.split('?')[0] == self.ticket_url:
self.driver.find_by_text('查詢').click()
sleep(1)
count += 1
print('第%d次點擊查詢……' % count)
try:
car_no_location = self.driver.find_by_id("queryLeftTable")[0].find_by_text(self.number)[0]
current_tr = car_no_location.find_by_xpath("./../../../../..")
if current_tr.find_by_tag('td')[self.seat_type_index].text == '--':
print('無此座位類型出售,已結束當前刷票,請重新開啟!')
sys.exit(1)
elif current_tr.find_by_tag('td')[self.seat_type_index].text == '無':
print('無票,繼續嘗試……')
elif current_tr.find_by_tag('td')[self.seat_type_index].text == '候補':
print('候補,繼續嘗試……')
else:
# 有票,嘗試預訂
print('刷到票了(余票數:' + str(current_tr.find_by_tag('td')[self.seat_type_index].text) + '),開始嘗試預訂……')
current_tr.find_by_css('td.no-br>a')[0].click()
sleep(1)
print('開始選擇用戶……')
key_value = 1
for p in self.passengers:
# 選擇用戶
self.driver.find_by_text(p).last.click()
# 選擇座位類型
seat_select = self.driver.find_by_id("seatType_" + str(key_value))[0]
seat_select.find_by_xpath("//option[@value='" + str(self.seat_type_value) + "']")[0].click()
key_value += 1
sleep(0.5)
if p[-1] == ')':
self.driver.find_by_id('dialog_xsertcj_ok').click()
print('正在提交訂單……')
self.driver.find_by_id('submitOrder_id').click()
sleep(0.5)
# 查看放回結果是否正常
submit_false_info = self.driver.find_by_id('orderResultInfo_id')[0].text
if submit_false_info != '':
print(submit_false_info)
self.driver.find_by_id('qr_closeTranforDialog_id').click()
sleep(0.2)
self.driver.find_by_id('preStep_id').click()
sleep(0.3)
continue
print('正在確認訂單……')
self.driver.find_by_id('submitOrder_id').click()
sleep(1)
print('預訂成功,請及時前往支付……')
# 發送內容
def mail_to(neirong, biaoti, geishei):
text = neirong
msg = MIMEText(text, 'plain', 'utf-8')
msg['subject'] = biaoti
msg["From"] = geishei
s = smtplib.SMTP(SMTPServer, 25)
s.login(sender, passwd)
s.sendmail(sender, sender, msg.as_string())
s.quit()
mail_to(neirong, biaoti, geishei)
#self.driver.quit()
except Exception as error_info:
print(error_info)
#self.driver.quit()
break
except Exception as error_info:
print(error_info)
self.driver.quit()
sys.exit(1)
if __name__ == '__main__':
# 城市cookie字典
city_list = {

'bj': '%u5317%u4EAC%2CBJP', # 北京
'hd': '%u5929%u6D25%2CTJP', # 邯鄲
'nn': '%u5357%u5B81%2CNNZ', # 南寧
'wh': '%u6B66%u6C49%2CWHN', # 武漢
'cs': '%u957F%u6C99%2CCSQ', # 長沙
'ty': '%u592A%u539F%2CTYV', # 太原
'yc': '%u8FD0%u57CE%2CYNV', # 運城
'gz': '%u5E7F%u5DDE%2CGZQ', # 廣州
'qhc': '%u6E05%u6CB3%u57CE%2CQYP' # 清河城
}
#郵件信息
SMTPServer = "smtp.163.com"
sender = "**********@163.com"
passwd = "********"
c = time.time()
b = time.localtime(c)
q = time.strftime("%Y-%m-%d %X", b)
neirong = ("12306:" + q + " 搶到票了,轉進時間吧!")
biaoti = ("一封信 " + q)
geishei = sender
# 從txt中獲取信息
with open(r'H:\For personal use\PYTHON\file\tickets.txt', 'r', encoding='utf-8', errors='ignore') as f:
info_array = np.genfromtxt(f, dtype=str, delimiter=':')
account = info_array[0][1]
password = info_array[1][1]
from_time = info_array[2][1]
start = info_array[3][1]
end = info_array[4][1]
from_station = city_list[start]
to_station = city_list[end]
number = info_array[5][1]
seat_type = info_array[6][1]
passengers = info_array[7][1].split(",")
#打印購票人信息
print(account, password, passengers, from_time, from_station, to_station, number, seat_type)
# 開始搶票
ticket = BrushTicket(account, password, passengers, from_time, from_station, to_station, number, seat_type)
ticket.start_brush()

When you don’t know what to do, just settle down and study!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved