哈嘍,哈嘍~,一年一度的搶火車票大戰(zhàn)正式拉開(kāi)序幕…
然餓大多數(shù)人碰到的是這種情況:當(dāng)你滿心期待摩拳擦掌準(zhǔn)備搶票的時(shí)候,你會(huì)發(fā)現(xiàn)一票難求!想回趟家真難!
那么作為程序猿的你,當(dāng)然要用程序猿的方式來(lái)?yè)屍?!下面分享用python來(lái)?yè)屍保?/p>
歡迎關(guān)注公眾號(hào):每日推薦系列,提供各種免費(fèi)資源!也可以咨詢代碼問(wèn)題哦!
城市cookie可根據(jù)具體需求自行添加!不懂的點(diǎn)這里!
- 導(dǎo)入所需模塊:
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
import time
此部分導(dǎo)入了代碼所需的各種模塊,用于實(shí)現(xiàn)不同的功能,包括正則表達(dá)式、網(wǎng)頁(yè)瀏覽、時(shí)間操作、系統(tǒng)相關(guān)操作、HTTP連接、URL解析、發(fā)送電子郵件和短信等功能。
- BrushTicket 類初始化:
class BrushTicket(object):
def __init__(self, passengers, from_time, from_station, to_station, number, seat_type, receiver_mobile, receiver_email):
# 初始化實(shí)例屬性
# ...
這部分定義了 BrushTicket
類并初始化了基于提供的參數(shù)的實(shí)例屬性。這些屬性包括乘客詳細(xì)信息、車站信息、出發(fā)時(shí)間、座位類型、通知聯(lián)系人和URL等。
- 登錄功能:
def do_login(self):
self.driver.visit(self.login_url)
sleep(1)
print('請(qǐng)掃描二維碼登錄或使用您的賬號(hào)登錄...')
while True:
if self.driver.url != self.init_my_url:
sleep(1)
else:
break
do_login
方法負(fù)責(zé)登錄網(wǎng)站。它打開(kāi)登錄的URL,等待用戶手動(dòng)登錄(可以通過(guò)掃描二維碼或使用賬號(hào)登錄),并等待登錄成功。
- 車票預(yù)訂功能:
def start_brush(self):
self.driver.driver.maximize_window()
self.do_login()
self.driver.visit(self.ticket_url)
try:
# ...
except Exception as error_info:
print(error_info)
start_brush
方法實(shí)現(xiàn)了車票預(yù)訂功能。它最大化瀏覽器窗口,執(zhí)行登錄操作,然后導(dǎo)航到車票預(yù)訂頁(yè)面。它不斷查詢是否有可用車票,選擇所需的座位類型,并嘗試為指定的乘客預(yù)訂車票。它還處理異常情況,并在成功預(yù)訂時(shí)提供通知。
- 短信通知:
def send_sms(self, mobile, sms_info):
# ...
send_sms
方法負(fù)責(zé)發(fā)送短信通知。它使用"互億無(wú)線"服務(wù)發(fā)送測(cè)試短信。它接收接收者的手機(jī)號(hào)碼和短信內(nèi)容作為參數(shù),并返回從服務(wù)端收到的響應(yīng)。
大家都有所體會(huì)12306那種神級(jí)驗(yàn)證碼,即使是聰明如你也不定每次都能把驗(yàn)證碼找對(duì)找全。然而經(jīng)過(guò)訓(xùn)練后的模型卻是可以的,不得不感嘆科技強(qiáng)大。當(dāng)然該程序中并沒(méi)有涉及到這一識(shí)別驗(yàn)證碼的核心技術(shù),它只是將這一工作丟給第三方若快平臺(tái)去做,然后自身利用結(jié)果即可。那么若快是如何識(shí)別這種神級(jí)驗(yàn)證碼呢?通過(guò)機(jī)器學(xué)習(xí) 訓(xùn)練所需要的模型?筆者在這方面所了解的較少,不能給過(guò)多解釋。但是這確實(shí)是個(gè)值得研究的方向。
- 郵件通知:
def send_mail(self, receiver_address, content):
# ...
send_mail
方法處理發(fā)送電子郵件通知的功能。它使用SMTP協(xié)議連接到電子郵件服務(wù)器,使用發(fā)件人的憑據(jù)登錄,并向指定的接收者地址發(fā)送電子郵件。它包括主題、正文以及發(fā)件人/收件人的詳細(xì)信息。它接收接收者的電子郵件地址和郵件內(nèi)容作為參數(shù)。
注:給我們推送相關(guān)消息,需要用戶去提供賬戶和密碼,這是個(gè)冒險(xiǎn)的嘗試,避免不了信息泄露的可能。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-605552.html
- 主程序執(zhí)行:
if __name__ == '__main__':
# 用戶輸入和初始化
# ...
# 開(kāi)始預(yù)訂車票
ticket = BrushTicket(passengers, from_time, from_station, to_station, number, seat_type, receiver_mobile, receiver_email)
ticket.start_brush()
主程序執(zhí)行部分接收用戶輸入以獲取預(yù)訂車票所需的各個(gè)參數(shù),使用提供的值初始化 BrushTicket
對(duì)象,并調(diào)用 start_brush
方法開(kāi)始預(yù)訂車票的過(guò)程。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-605552.html
注意?。。∫韵率荘ython部分主要代碼:
歡迎前往公眾號(hào):每日推薦系列,回復(fù)【12306搶票】獲取源碼!
def start_brush(self):
"""買票功能實(shí)現(xiàn)"""
# 瀏覽器窗口最大化
self.driver.driver.maximize_window()
# 登陸
self.do_login()
# 跳轉(zhuǎn)到搶票頁(yè)面
self.driver.visit(self.ticket_url)
try:
print('開(kāi)始刷票……')
# 加載車票查詢信息
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 == self.ticket_url:
try:
self.driver.find_by_text('查詢').click()
except Exception as error_info:
print(error_info)
sleep(1)
continue
sleep(0.2)
count += 1
local_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('第%d次點(diǎn)擊查詢……[%s]' % (count, local_date))
try:
current_tr = self.driver.find_by_xpath(
'//tr[@datatran="' + self.number + '"]/preceding-sibling::tr[1]')
if current_tr:
if current_tr.find_by_tag('td')[self.seat_type_index].text == '--':
print('無(wú)此座位類型出售,已結(jié)束當(dāng)前刷票,請(qǐng)重新開(kāi)啟!')
sys.exit(1)
elif current_tr.find_by_tag('td')[self.seat_type_index].text == '無(wú)':
print('無(wú)票,繼續(xù)嘗試……')
sleep(1)
else:
# 有票,嘗試預(yù)訂
print('刷到票了(余票數(shù):' + str(
current_tr.find_by_tag('td')[self.seat_type_index].text) + '),開(kāi)始嘗試預(yù)訂……')
current_tr.find_by_css('td.no-br>a')[0].click()
sleep(1)
key_value = 1
for p in self.passengers:
if '()' in p:
p = p[:-1] + '學(xué)生' + p[-1:]
# 選擇用戶
print('開(kāi)始選擇用戶……')
self.driver.find_by_text(p).last.click()
# 選擇座位類型
print('開(kāi)始選擇席別……')
if self.seat_type_value != 0:
self.driver.find_by_xpath(
"http://select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(
self.seat_type_value) + "']").first.click()
key_value += 1
sleep(0.2)
if p[-1] == ')':
self.driver.find_by_id('dialog_xsertcj_ok').click()
print('正在提交訂單……')
self.driver.find_by_id('submitOrder_id').click()
sleep(2)
# 查看放回結(jié)果是否正常
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('正在確認(rèn)訂單……')
self.driver.find_by_id('qr_submit_id').click()
print('預(yù)訂成功,請(qǐng)及時(shí)前往支付……')
# 發(fā)送通知信息
self.send_mail(self.receiver_email, '恭喜您,搶到票了,請(qǐng)及時(shí)前往12306支付訂單!')
self.send_sms(self.receiver_mobile, '您的驗(yàn)證碼是:1230。請(qǐng)不要把驗(yàn)證碼泄露給其他人。')
else:
print('不存在當(dāng)前車次【%s】,已結(jié)束當(dāng)前刷票,請(qǐng)重新開(kāi)啟!' % self.number)
sys.exit(1)
except Exception as error_info:
print(error_info)
# 跳轉(zhuǎn)到搶票頁(yè)面
self.driver.visit(self.ticket_url)
except Exception as error_info:
print(error_info)
def send_sms(self, mobile, sms_info):
"""發(fā)送手機(jī)通知短信,用的是-互億無(wú)線-的測(cè)試短信"""
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):
"""發(fā)送郵件通知"""
# 連接郵箱服務(wù)器信息
host = 'smtp.163.com'
port = 25
sender = 'gxcuizy@163.com' # 你的發(fā)件郵箱號(hào)碼
pwd = '******' # 不是登陸密碼,是客戶端授權(quán)密碼
# 發(fā)件信息
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)
# 開(kāi)始登陸郵箱,并發(fā)送郵件
s.login(sender, pwd)
s.sendmail(sender, receiver, msg.as_string())
到了這里,關(guān)于手把手教你用python一鍵搶12306火車票(附代碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!