有身在异乡的小伙伴们?相信绝大多数的小伙伴都曾有过离开过,或现在是,独在异乡的情况吧,拿小编来说,小编现在就是这种状况,回家次数不多,不是因为没有时间,而是因为没有车票,每次都需要拿抢票软件,于是,脑海中,就印出这么个奇怪内容,为什么抢票软件能准确找到票呢?
先来看一下该程序的思路图:
执行
该程序使用 Python 创建,支持版本为 2.7.10 - 2.7.15。
依赖
依赖库包括:用来对付 12306「刺激」验证码的图像识别工具(该 repo 中推荐使用若快);项目依赖包 requirements.txt。
按照如下命令安装项目依赖包:
pipinstall-ihttps://pypi.tuna.tsinghua.edu.cn/simple-rrequirements.txt
项目使用说明
1、定义自动购票的类(初始化属性)
classBuy_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、实现登录功能
deflogin(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('请输入验证码...') whileTrue: ifself.driver.url!=self.initMy_url: sleep(1) else: Break
3、实现购票功能
defstart_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 ifself.order!=0: whileself.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) exceptExceptionase: print(e) print('预订失败...') Continue
以上就可以爬取到车票了哦~感兴趣的小伙伴可以试试呢~关于python好玩内容特别多,大家又兴趣的都可以去学习了解下的哦~