這個腳本目前只能刷一趟車的,人數可以是多個,支持選取作為類型等。實現思路是splinter.browser模擬瀏覽器登陸和操作,由于12306的驗證碼不好自動識別,所以,驗證碼需要用戶進行手動識別,并進行登陸操作,之后的事情,就交由腳本來操作就可以了,下面是我測試時候的一些截圖:
第一步:如下圖,首先輸入搶票基本信息
第二步:然后進入登錄頁,需要手動輸入驗證碼,并點擊登陸操作
第三步:登陸后,自動進入到搶票頁面,如下圖這樣的
最后:就是坐等刷票結果就好了,如下圖這樣,就說是刷票成功了,刷到票后,會進行短信和郵件的通知,請記得及時前往12306進行支付,不然就白搶了。
Python運行環境:python3.6用到的模塊:re、splinter、time、sys、httplib2、urllib、smtplib、email未安裝的模塊,請使用pip instatll進行安裝,例如:pip install splinter如下代碼是這個腳本所有用到的模塊引入:
import re
from splinter.browser import Browser
from time import sleep
import sys
import httplib2
from urllib import parse
import smtplib
from email.mime.text import MIMEText
復制代碼
刷票前信息準備,我主要說一下始發站和目的地的cookie值獲取,因為輸入城市的時候,需要通過cookie值,cookie值可以通過12306官網,然后在F12(相信所有的coder都知道這個吧)的network里面的查詢請求cookie中可以看到,在請求的header里面可以找到,_jc_save_fromStation值是出發站的cookie,_jc_save_toStation的值是目的地的cookie,然后加入到代碼里的城市的cookie字典city_list里即可,鍵是城市的首字母,值是cookie值的形式。
搶票,肯定需要先登錄,我這里模擬的登錄操作,會自動填充12306的賬號名和密碼,當然,你也可以在打開的瀏覽器中修改賬號和密碼,實現的關鍵代碼如下:
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
復制代碼
登錄之后,就是控制刷票的各種操作處理了,這里,我就不貼代碼了,因為代碼比較多,別擔心,在最后,我會貼出完整的代碼的。
當刷票成功后,我會進行短信和郵件的雙重通知,當然,這里短信通知的平臺,就看你用那個具體來修改代碼了,我用的是互億無線的體驗版的免費短信通知接口;發送郵件模塊我用的是smtplib,發送郵件服務器用的是163郵箱,如果用163郵箱的話,你還沒有設置客戶端授權密碼,記得先設置客戶端授權密碼就好了,挺方便的。以下是主要實現代碼:
def send_sms(self, mobile, sms_info):
"""發送手機通知短信,用的是-互億無線-的測試短信"""
host="106.ihuyi.com"
sms_send_uri="/webservice/sms.php?method=Submit"
account="C59782899"
pass_word="19d4d9c0796532c7328e8b82e2812655"
params=parse.urlencode(
{'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'}
)
headers={"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn=httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)
conn.request("POST", sms_send_uri, params, headers)
response=conn.getresponse()
response_str=response.read()
conn.close()
return response_str
def send_mail(self, receiver_address, content):
"""發送郵件通知"""
# 連接郵箱服務器信息
host='smtp.163.com'
port=25
sender='xxxxxx@163.com' # 你的發件郵箱號碼
pwd='******' # 不是登陸密碼,是客戶端授權密碼
# 發件信息
receiver=receiver_address
body='<h2>溫馨提醒:</h2><p>' + content + '</p>'
msg=MIMEText(body, 'html', _charset="utf-8")
msg['subject']='搶票成功通知!'
msg['from']=sender
msg['to']=receiver
s=smtplib.SMTP(host, port)
# 開始登陸郵箱,并發送郵件
s.login(sender, pwd)
s.sendmail(sender, receiver, msg.as_string())
復制代碼
說了那么多,感覺都是說了好多廢話啊,哈哈,不好意思,耽誤大家時間來看我瞎扯了,我貼上大家最關心的源碼,請接碼,大家在嘗試運行過程中,有任何問題,可以給我留言或者私信我,我看到都會及時回復大家的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
通過splinter刷12306火車票
可以自動填充賬號密碼,同時,在登錄時,也可以修改賬號密碼
然后手動識別驗證碼,并登陸,接下來的事情,交由腳本來做了,靜靜的等待搶票結果就好(刷票過程中,瀏覽器不可關閉)
author: cuizy
time: 2018-05-30
"""
import re
from splinter.browser import Browser
from time import sleep
import sys
import httplib2
from urllib import parse
import smtplib
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, receiver_mobile, receiver_email):
"""定義實例屬性,初始化"""
# 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.receiver_mobile=receiver_mobile
self.receiver_email=receiver_email
# 主要頁面網址
self.login_url='https://kyfw.12306.cn/otn/login/init'
self.init_my_url='https://kyfw.12306.cn/otn/index/initMy12306'
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='C:\\Users\cuizy\AppData\Local\Programs\Python\Python36\Scripts\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(900, 700)
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)[1]
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('無票,繼續嘗試……')
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)
key_value=1
for p in self.passengers:
# 選擇用戶
print('開始選擇用戶……')
self.driver.find_by_text(p).last.click()
# 選擇座位類型
print('開始選擇席別……')
if self.seat_type_value !=0:
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(2)
# 查看放回結果是否正常
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('qr_submit_id').click()
print('預訂成功,請及時前往支付……')
# 發送通知信息
self.send_mail(self.receiver_email, '恭喜您,搶到票了,請及時前往12306支付訂單!')
self.send_sms(self.receiver_mobile, '您的驗證碼是:8888。請不要把驗證碼泄露給其他人。')
except Exception as error_info:
print(error_info)
except Exception as error_info:
print(error_info)
def send_sms(self, mobile, sms_info):
"""發送手機通知短信,用的是-互億無線-的測試短信"""
host="106.ihuyi.com"
sms_send_uri="/webservice/sms.php?method=Submit"
account="C59782899"
pass_word="19d4d9c0796532c7328e8b82e2812655"
params=parse.urlencode(
{'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'}
)
headers={"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn=httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)
conn.request("POST", sms_send_uri, params, headers)
response=conn.getresponse()
response_str=response.read()
conn.close()
return response_str
def send_mail(self, receiver_address, content):
"""發送郵件通知"""
# 連接郵箱服務器信息
host='smtp.163.com'
port=25
sender='******@163.com' # 你的發件郵箱號碼
pwd='******' # 不是登陸密碼,是客戶端授權密碼
# 發件信息
receiver=receiver_address
body='<h2>溫馨提醒:</h2><p>' + content + '</p>'
msg=MIMEText(body, 'html', _charset="utf-8")
msg['subject']='搶票成功通知!'
msg['from']=sender
msg['to']=receiver
s=smtplib.SMTP(host, port)
# 開始登陸郵箱,并發送郵件
s.login(sender, pwd)
s.sendmail(sender, receiver, msg.as_string())
if __name__=='__main__':
# 12306用戶名
user_name=input('請輸入12306用戶名:')
while user_name=='':
user_name=input('12306用戶名不能為空,請重新輸入:')
# 12306登陸密碼
password=input('請輸入12306登陸密碼:')
while password=='':
password=input('12306登陸密碼不能為空,請重新輸入:')
# 乘客姓名
passengers_input=input('請輸入乘車人姓名,多人用英文逗號“,”連接,(例如單人“張三”或者多人“張三,李四”):')
passengers=passengers_input.split(",")
while passengers_input=='' or len(passengers) > 4:
print('乘車人最少1位,最多4位!')
passengers_input=input('請重新輸入乘車人姓名,多人用英文逗號“,”連接,(例如單人“張三”或者多人“張三,李四”):')
passengers=passengers_input.split(",")
# 乘車日期
from_time=input('請輸入乘車日期(例如“2018-08-08”):')
date_pattern=re.compile(r'^\d{4}-\d{2}-\d{2}$')
while from_time=='' or re.findall(date_pattern, from_time)==[]:
from_time=input('乘車日期不能為空或者時間格式不正確,請重新輸入:')
# 城市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', # 運城
'gzn': '%u5E7F%u5DDE%u5357%2CIZQ', # 廣州南
'wzn': '%u68A7%u5DDE%u5357%2CWBZ', # 梧州南
}
# 出發站
from_input=input('請輸入出發站,只需要輸入首字母就行(例如北京“bj”):')
while from_input not in city_list.keys():
from_input=input('出發站不能為空或不支持當前出發站(如有需要,請聯系管理員!),請重新輸入:')
from_station=city_list[from_input]
# 終點站
to_input=input('請輸入終點站,只需要輸入首字母就行(例如北京“bj”):')
while to_input not in city_list.keys():
to_input=input('終點站不能為空或不支持當前終點站(如有需要,請聯系管理員!),請重新輸入:')
to_station=city_list[to_input]
# 車次編號
number=input('請輸入車次號(例如“G110”):')
while number=='':
number=input('車次號不能為空,請重新輸入:')
# 座位類型
seat_type=input('請輸入座位類型(例如“軟臥”):')
while seat_type=='':
seat_type=input('座位類型不能為空,請重新輸入:')
# 搶票成功,通知該手機號碼
receiver_mobile=input('請預留一個手機號碼,方便搶到票后進行通知(例如:18888888888):')
mobile_pattern=re.compile(r'^1{1}\d{10}$')
while receiver_mobile=='' or re.findall(mobile_pattern, receiver_mobile)==[]:
receiver_mobile=input('預留手機號碼不能為空或者格式不正確,請重新輸入:')
receiver_email=input('請預留一個郵箱,方便搶到票后進行通知(例如:test@163.com):')
while receiver_email=='':
receiver_email=input('預留郵箱不能為空,請重新輸入:')
# 開始搶票
ticket=BrushTicket(user_name, password, passengers, from_time, from_station, to_station, number, seat_type, receiver_mobile, receiver_email)
ticket.start_brush()
文章到此結束嘍,喜歡的給小編點點關注奧,多多轉發收藏,感謝大家!
序很簡單,主要是調用了12306的api。用法也很簡單:輸入出發地、目的地、乘車時間,將查詢到的結果在命令行打印出來。對了,這個是我以前參照了:Python3 實現火車票查詢工具_Python_實驗樓 - 實驗樓 ,現在我把簡單修改了一下,適合新人練練手!
有兩點需要注意:
1.from stations import stations這個是stations是個存儲城市和代碼的字典{},譬如南京,對應的城市代碼是NKH,這個就是在stations里查找得出的。
2.主要用到了colorama,docopt,prettytable可以將命令行的查詢結果以彩色表格形式打印。
3.用到了while True....這樣可以保證程序一直循環,查詢一次,輸出結果以后,再次開始新一輪的查詢。如果需要中斷程序可以用ctrl+c。
使用方法如下:
"""
Usage:
輸入要查詢的火車類型可以多選(動車d,高鐵g,特快t,快速k,直達z)
輸入出發地、目的地、出發日期。
查詢結果以命令行形式自動呈現。
Examples:
Please input the trainType you want to search :dgz
Please input the city you want leave :南京
Please input the city you will arrive :北京
Please input the date(Example:2017-09-27) :2018-03-01
"""
程序截圖如下:
動態效果如下:
<script src="https://lf3-cdn-tos.bytescm.com/obj/cdn-static-resource/tt_player/tt.player.js?v=20160723"></script>
程序源代碼,包含兩部分:1.stations.py 2.searchTrain.py
1.stations.py
import re
import requests
from pprint import pprint
url='https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9018'
requests.packages.urllib3.disable_warnings()#如果不加此句會有:InsecureRequestWarning: Unverified HTTPS request is being made
html=requests.get(url,verify=False)
station=re.findall(u'([\u4e00-\u9fa5]+)\|([A-Z]+)', html.text)
stations=dict(station)
pprint(stations,indent=4)
2.searchTrain.py
"""
Usage:
輸入要查詢的火車類型可以多選(動車d,高鐵g,特快t,快速k,直達z)
輸入出發地、目的地、出發日期。
查詢結果以命令行形式自動呈現。
Examples:
Please input the trainType you want to search :dgz
Please input the city you want leave :南京
Please input the city you will arrive :北京
Please input the date(Example:2017-09-27) :2018-03-01
"""
#coding=utf-8
#author=Lyon
#date=2017-12-17
import json
import requests
from docopt import docopt
from prettytable import PrettyTable
from colorama import init,Fore
from stations import stations
class searchTrain:
def __init__(self):
self.trainOption=input('-d動車 -g高鐵 -k快速 -t特快 -z直達,Please input the trainType you want to search :')
self.fromStation=input('Please input the city you want leave :')
self.toStation=input('Please input the city you will arrive :')
self.tripDate=input('Please input the date(Example:2017-09-27) :')
self.headers={
"Cookie":"自定義",
"User-Agent": "自定義",
}
self.available_trains,self.options=self.searchTrain()
@property
def trains(self):
for item in self.available_trains:
cm=item.split('|')
train_no=cm[3]
initial=train_no[0].lower()
if not self.options or initial in self.options:
train=[
train_no,
'\n'.join([Fore.GREEN + cm[6] + Fore.RESET,
Fore.RED + cm[7] + Fore.RESET]),
'\n'.join([Fore.GREEN + cm[8] + Fore.RESET,
Fore.RED + cm[9] + Fore.RESET]),
cm[10],
cm[32],
cm[25],
cm[31],
cm[30],
cm[21],
cm[23],
cm[28],
cm[24],
cm[29],
cm[26],
cm[22] ]
yield train
def pretty_print(self):
pt=PrettyTable()
header='車次 車站 時間 歷時 商務座 特等座 一等 二等 高級軟臥 軟臥 硬臥 軟座 硬座 無座 其他'.split()
pt._set_field_names(header)
for train in self.trains:
pt.add_row(train)
print(pt)
def searchTrain(self):
arguments={
'option':self.trainOption,
'from':self.fromStation,
'to':self.toStation,
'date':self.tripDate
}
options=''.join([item for item in arguments['option']])
from_station, to_station, date=stations[arguments['from']] , stations[arguments['to']] , arguments['date']
url=('https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT').format(date,from_station,to_station)
requests.packages.urllib3.disable_warnings()
html=requests.get(url,headers=self.headers,verify=False)
available_trains=html.json()['data']['result']
return available_trains,options
if __name__=='__main__':
while True:
asd=searchTrain()
asd.pretty_print()
后續:其實查詢還是很簡單的,就是調用API接口,輸入查詢關鍵詞就OK了,但是要想完整地實現購買火車票的流程,還是一個比較復雜的項目,Github上有完整的項目,喜歡的童鞋可以上去看看~testerSunshine/12306
彩蛋:
下一篇文章:Python命令行實現—查全國7天天氣
下下篇文章:Python—itchat實現微信自動回復
下下下篇文章:Python實現微信查天氣+火車+飛機+快遞!!!
項目為前幾天收費幫學妹做的一個項目,Java EE JSP項目,在工作環境中基本使用不到,但是很多學校把這個當作編程入門的項目來做,故分享出本項目供初學者參考。
SpringBoot火車票系統
系統有1權限:用戶
技術棧:SpringBoot
登錄
注冊
首頁
訂單
查看火車票訂單信息
退票功能
火車票
查詢火車票
購票功能
個人信息
展示與修改
訪問地址 :
http://localhost:8080/static/fontpage/login.html
賬號密碼
賬戶:12
密碼:33
*請認真填寫需求信息,我們會在24小時內與您取得聯系。