python搶票(帶配置文件)

源碼如下:

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

from splinter.browser import Browser
from time import sleep
import os
# from selenium.webdriver.chrome.options import Options
import logging
from log_class import Logger
import yaml
import sys

reload(sys)
sys.setdefaultencoding('utf-8')  # 防止由於Unicode編碼與ASCII編碼的不兼容造成錯誤

class BuyTicket(object):
    def __init__(self, username, passwd, order, passengers, seatType, ticketType, daytime, starts, ends):
        # 用戶名 密碼
        self.username = username
        self.passwd = passwd
        # 車次,選擇第幾趟,0則從上之下依次點擊
        self.order = order
        # 乘客名
        self.passengers = passengers
        # 席位
        self.seatType = seatType
        self.ticketType = ticketType
        # 時間格式2018-02-05
        self.daytime = daytime
        # 起始地和終點
        self.starts = starts
        self.ends = ends

        self.login_url = 'https://kyfw.12306.cn/otn/login/init'
        self.initMy_url = 'https://kyfw.12306.cn/otn/index/initMy12306'
        self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'
        # 瀏覽器名稱
        self.driver_name = 'firefox'  # chrome firefox
        # 火狐瀏覽器第三方驅動
        self.executable_path = os.getcwd()+'/geckodriver'  # 獲取工程目錄下的火狐驅動 chromedriver

    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)
        logbticket.info("請手動輸入驗證碼...")
        # print('請手動輸入驗證碼...')  # 目前沒有自動驗證碼
        # 循環等待登錄,登錄成功,跳出循環
        while True:
            if self.driver.url != self.initMy_url:
                sleep(1)
            else:
                break

    def start_buy(self):
        # 這些設置都是必要的
        # chrome_options = Options()
        # chrome_options.add_argument("--no-sandbox")
        # chrome_options.add_argument("--disable-setuid-sandbox")
        # chrome_options.add_argument("disable-infobars")  # 禁用網頁上部的提示欄
        # self.driver = Browser(driver_name=self.driver_name, options=chrome_options, executable_path=self.executable_path)
        self.driver = Browser(driver_name=self.driver_name,
                              executable_path=self.executable_path)
        # 設置窗口大小尺寸
        self.driver.driver.set_window_size(1400, 1000)
        # 用戶登錄
        self.login()
        # 進入選票網站
        self.driver.visit(self.ticket_url)
        try:
            logbticket.info("購票頁面開始....")
            # 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.daytime})

            self.driver.reload()

            count = 0
            if self.order != 0:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text("查詢").click()
                    count = count+1
                    logbticket.info("第 %d 次點擊查詢..." % count)
                    # print("第 %d 次點擊查詢..." % count)
                    # sleep(1)
                    try:
                        self.driver.find_by_text("預訂")[self.order - 1].click()  # 點擊第幾個“預訂”
                        sleep(1.5)
                    except Exception as e:  # e是Exception 的一個instance
                        # print(e)
                        # print("預訂失敗...")
                        logbticket.error(e)
                        logbticket.error("預訂失敗...")
                        continue
            else:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text("查詢").click()
                    count += 1
                    logbticket.info("第 %d 次點擊查詢..." % count)
                    # print("第 %d 次點擊查詢..." % count)
                    try:
                        for i in self.driver.find_by_text("預訂"):
                            i.click()
                            sleep(1)
                    except Exception as e:
                        # print(e)
                        # print("預訂失敗...")
                        logbticket.error(e)
                        logbticket.error("預訂失敗...")
                        continue

            # print("開始預訂....")
            logbticket.info("開始預訂....")
            # sleep(1)
            # self.driver.reload()
            sleep(1)
            # print("開始選擇用戶....")
            logbticket.info("開始選擇用戶....")
            for p in self.passengers:
                pg = self.driver.find_by_text(p)  # .last.click()
                pg.last.click()
            # print("提交訂單....")
            logbticket.info("提交訂單....")
            sleep(1)
            i = 0
            while len(self.passengers) > 0:
                i = i + 1
                seat_id_string = "seatType_" + str(i)
                ticket_id_string = "ticketType_" + str(i)
                self.driver.find_by_xpath('//select[@id="%s"]/option[@value="%s"]'
                                          % (seat_id_string, self.seatType)).first._element.click()
                self.driver.find_by_xpath('//select[@id="%s"]//option[@value="%s"]'
                                          % (ticket_id_string, self.ticketType)).first._element.click()
                self.passengers.pop()
                sleep(1)
            self.driver.find_by_id("submitOrder_id").click()
            # print("開始選座...")
            logbticket.info("開始選座...")
            sleep(1.5)
            # print("確認選座....")
            logbticket.info("確認選座....")
            self.driver.find_by_text("qr_submit_id").click()

        except Exception as e:
            # print(e)
            logbticket.error(e)


city = {"深圳": "%u6DF1%u5733%2CSZQ",
        "武漢": "%u6B66%u6C49%2CWHN",
        "隨州": "%u968F%u5DDE%2CSZN"}

seatT = {"硬臥": "3",
         "軟臥": "4",
         "硬座": "1",
         "二等座": "O",
         "一等座": "M",
         "商務座": "9"}

ticketT = {"成人票": "1"}

if __name__ == '__main__':
    # # 用戶名
    # username = "hugoodboy"
    # # 密碼
    # password = "198324"
    # # 車次選擇,0代表所有車次
    # order = 3
    # # 乘客名,比如passengers = ['丁小紅', '丁小明']
    # # 學生票需註明,註明方式爲:passengers = ['丁小紅(學生)', '丁小明']
    # passengers = ["胡迎春", "柳淑瓊"]
    # # 日期,格式爲:'2018-01-20'
    # daytime = "2018-04-18"
    # # 出發地(需填寫cookie值)
    # starts = city["武漢"]  # 武漢
    # # 目的地(需填寫cookie值)
    # ends = city["深圳"]  # 深圳
    # # 席別
    # seatType = "一等座"  # 軟臥
    # # 票種
    # ticketType = "1"  # 成人票

    logbticket = Logger("bticket.log", logging.DEBUG, logging.ERROR)
    try:
        with open("profile.yml", "r") as f:
            btconfig = yaml.safe_load(f)
    except OSError:
        logbticket.error("Can't open config file: profile.yml")
        raise

    # 用戶名
    username = btconfig['username']
    # 密碼
    password = btconfig['password']
    # 車次選擇,0代表所有車次
    order = btconfig['order']
    # 乘客名,比如passengers = ['丁小紅', '丁小明']
    passengers = btconfig['passengers']
    # 日期,格式爲:'2018-01-20'
    daytime = btconfig['daytime']
    # 出發地(需填寫cookie值)
    # cfgstart = btconfig['starts']
    starts = city[btconfig['starts'].encode('utf-8')]  # 武漢,將unicode格式編碼爲utf-8格式
    # 目的地(需填寫cookie值)
    # cfgend = btconfig['ends']
    ends = city[btconfig['ends'].encode('utf-8')]  # 北京,將unicode格式編碼爲utf-8格式
    # 席別
    seatType = seatT[btconfig['seatType'].encode('utf-8')]  # 二等座,將unicode格式編碼爲utf-8格式
    # 票種
    ticketType = ticketT[btconfig['ticketType'].encode('utf-8')]  # 成人票,將unicode格式編碼爲utf-8格式

    BuyTicket(username, password, order, passengers, seatType, ticketType, daytime, starts, ends).start_buy()

python Splinter 12306搶票 地址:https://blog.csdn.net/lijing198997/article/details/79746601

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章