有身在异乡的小伙伴们?相信绝大多数的小伙伴都曾有过离开过,或现在是,独在异乡的情况吧,拿小编来说,小编现在就是这种状况,回家次数不多,不是因为没有时间,而是因为没有车票,每次都需要拿抢票软件,于是,脑海中,就印出这么个奇怪内容,为什么抢票软件能准确找到票呢?先来看一下该程序的思路图:

执行
该程序使用 Python 创建,支持版本为 2.7.10 - 2.7.15。
依赖
依赖库包括:用来对付 12306「刺激」验证码的图像识别工具(该 repo 中推荐使用若快);项目依赖包 requirements.txt。
按照如下命令安装项目依赖包:
项目使用说明
1、定义自动购票的类(初始化属性)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Buy_Tickets(object):
# 定义实例属性,初始化
def __init__(self, username, passwd, order, passengers, dtime, starts, ends):
self.username = username
self.passwd = passwd
self.order = order # 车次,0代表所有车次
self.passengers = passengers # 乘客名
self.starts = starts # 起始地和终点
self.ends = ends
self.dtime = dtime # 日期
self.login_url = 'https://kyfw.12306.cn/otn/login/init'
self.initMy_url = 'https://kyfw.12306.cn/otn/view/index.html'
self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'
self.driver_name = 'chrome'
self.executable_path = 'C:\python\chromedriver.exe'
|
2、实现登录功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | def login(self):
self.driver.visit(self.login_url)
self.driver.fill( 'loginUserDTO.user_name' , self.username)
# sleep(1)
self.driver.fill( 'userDTO.password' , self.passwd)
# sleep(1)
print( '请输入验证码...' )
while True:
if self.driver.url != self.initMy_url:
sleep(1)
else :
Break
|
3、实现购票功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | def start_buy(self):
self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)
# 窗口大小的操作
self.driver.driver.set_window_size(1200, 700)
self.login()
self.driver.visit(self.ticket_url)
try :
print( '开始购票...' )
# 加载查询信息
self.driver.cookies.add({ "_jc_save_fromStation" : self.starts})
self.driver.cookies.add({ "_jc_save_toStation" : self.ends})
self.driver.cookies.add({ "_jc_save_fromDate" : self.dtime})
self.driver.reload()
count = 0
if self.order != 0:
while self.driver.url == self.ticket_url:
self.driver.find_by_text( '查询' ).click()
count += 1
print( '第%d次点击查询...' % count)
try :
self.driver.find_by_text( '预订' )[self.order - 1].click()
sleep(1.5)
except Exception as e:
print(e)
print( '预订失败...' )
Continue
|
以上就可以爬取到车票了哦~感兴趣的小伙伴可以试试呢~关于python好玩内容特别多,大家又兴趣的都可以去学习了解下的哦~