Python 一百多行实现抢票助手

一. 代码使用Python+Splinter开发,Splinter是一个使用Python开发的开源Web应用测试工具,它可以帮你实现自动浏览站点和与其进行交互。
二. 安装好Python 3或2都可以,然后安装Splinter  `pip install Splinter`
三. Splinter注意事项
    1. Splinter的Browser类默认优先使用firefox,所以用chrome的话,需要指定driver_name="chrome",只要养成一个习惯,不管用什么浏览器都指定,问题会出得少
    2. 当然,选择chrome的话,需要查看自己浏览器的版本,需要和chromedriver版本对应(不是版本号一致),参考和下载地址是http://blog.csdn.net/huilan_same/article/details/51896672
四. Splinter.broser部分方法介绍
    1.  findbyid("控件id").first:根据id找到组件
    2.  visis(url):访问指定网址
    3.  fill("填充的内容"):用指定内容填充组件
    4.  click():点击事件
    5.  reload():重新加载当前文档
五. 主要思路:
    1. 自动填充用户名,密码,点击图片验证码(手动),自动点击购票查询,预订,自动选择指定乘客进入提交订单页面
    2. 除登录时的图片验证码,全程自动
六. error(下面是我已经尝试成功的):
    1. OSError: [WinError 193] %1 不是有效的 Win32 应用程序。
    2. 解决方案:chromedriver版本和电脑浏览器版本映射没对应
    3. ImportError: cannot import name 'Browser'。
    4. 解决方案:是否安装了Splinter  `pip install Splinter`,将代码文件和chromedriver放到一个新文件夹下,防止其他文件的影响
    5. 请在运行文件前,将代码内的乘客,用户名,密码正确填写好,检查cookies是否正确
七. cookies 查看
    1. 进入chrome浏览器,按F12,选中NetWork选项,如下图
    
     2. 起始地址: `_jc_save_fromStation` 购票时间: `_jc_save_fromDate` 目的地: `_jc_save_toStation`

八.  运行方法
    1. python trainticket.py 天津 南昌 2018-02-10
    2. OK

九.  具体代码如下

 
  # -*- coding:utf-8 -*-
    """
    @author Jianxiong Rao
    """
    from splinter.browser import Browser
    from time import sleep
    import traceback
    import time,sys
    import os
    
    class HuoChe(object):
        """docstring for Train"""
        driver_name=''
        executable_path=''
        #用户名 密码
        username = u"12306帐户名"
        passwd = u"12306密码"
        #cookies值自己找 
        # 天津%u5929%u6D25%2CTJP 南昌%u5357%u660C%2CNCG 桂林%u6842%u6797%2CGLZ
        starts = u"%u5929%u6D25%2CTJP"
        ends = u"%u5357%u660C%2CNCG"
        #时间格式2018-02-05
        dtime = u"2018-02-05"
        #车次,选择第几趟,0则从上之下依次点击
        order = 0
        ###乘客姓名
        users=[u'乘客名']
        ##席位
        xb=u"二等座"
        pz=u"成人票"
        """网址"""
        #12306查询URL
        ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init"
        #12306登录URL
        login_url = "https://kyfw.12306.cn/otn/login/init"
        #我的12306URL
        initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306"
        #购票URL
        buy="https://kyfw.12306.cn/otn/confirmPassenger/initDc"
        login_url='https://kyfw.12306.cn/otn/login/init'
    
        def __init__(self):
            self.driver_name = 'chrome'
            self.executable_path = os.getcwd()+'/chromedriver'
            print("Welcome To Use The Tool")
        
        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)
            print("等待验证码,自行输入....")
            while True:
                if self.driver.url != self.initmy_url:
                    sleep(1)
                else :
                    break
        def start(self):
            self.driver = Browser(driver_name=self.driver_name,executable_path = self.executable_path)
            self.driver.driver.set_window_size(1400,1000)
            self.login()
            #sleep(1)
            self.driver.visit(self.ticket_url)
            try:
                print("购票页面开始....")
                #sleep(1)
                #加载查询信息
                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_bytext(u"查询").click()
                        count += 1
                        print("循环点击查询.... 第 %s 次"%count)
                        #sleep(1)
                        try:
                            self.driver.find_by_text(u'预订')[self.order - 1].click()
                        except Exception as e:
                            print(e)
                            print("还没开始预订")
                            continue
                else :
                    while self.driver.url == self.ticket_url:
                        self.driver.find_by_text(u"查询").click()
                        count += 1
                        print("循环点击查询.... 第 %s 次"%count)
                        #sleep(0.8)
                        try:
                            for i in self.driver.find_by_text(u"预订"):
                                i.click()
                                sleep(1)
                        except Exception as e:
                            print(e)
                            print("还没开始预订 %s "%count)
                            continue
                print("开始预订....")
                #sleep(1)
                #self.driver.reload()
                sleep(1)
                print("开始选择用户....")
                for user in self.users:
                    self.driver.find_by_text(user).last.click()
                print("提交订单....")
                sleep(1)
                # self.driver.find_by_text(self.pz).click()
                # self.driver.find_by_id('').select(self.pz)
                # sleep(1)
                # self.driver.find_by_text(self.xb).click()
                # sleep(1)
                self.driver.find_by_id('submitOrder_id').click()
                print("开始选座...")
                # self.driver.find_by_id('1D').last.click()
                # self.driver.find_by_id('1F').last.click()
                sleep(1.5)
                print("确认选座....")
                self.driver.find_by_text('qr_submit_id').click()
    
            except Exception as e:
                print(e)
    
    cities={
    '天津':'%u5929%u6D25%2CTJP',
    '南昌':'%u5357%u660C%2CNCG',
    '桂林':'%u6842%u6797%2CGLZ'
    }
    
    if __name__=="__main__":
        train = HuoChe()
        train.starts = cities[sys.argv[1]]
        train.ends = cities[sys.argv[2]]
        train.dtime = sys.argv[3]
        train.start()
十.  源码地址

  如有错误,请纠正,谢谢!

猜你喜欢

转载自blog.csdn.net/tenderness4/article/details/79275557