1. 程式人生 > >Python 一百多行實現搶票助手

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()
十.原始碼地址

  如有錯誤,請糾正,謝謝!