1. 程式人生 > >基於selenium的12306搶票

基於selenium的12306搶票

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class Qiangpiao(object):
    def __init__(self):
        # 登入的url
        self.login_url = "https://kyfw.12306.cn/otn/login/init"
        # 登入成功後的url
        self.init_my_url = "https://kyfw.12306.cn/otn/index/initMy12306"
        # 查詢餘票介面
        self.search_url = "https://kyfw.12306.cn/otn/leftTicket/init"
        self.driver = webdriver.Chrome()


    def wait_input(self):
        self.from_station = input("出發地:")
        self.to_station = input("目的地:")
        # 時間格式必須是:yyyy-MM-dd
        self.depart_time = input("出發時間:")
        self.passengers = input("乘客姓名(如有多個乘客,用英文逗號隔開):").split(",")
        self.trains = input("車次(如有多個車次,用英文逗號隔開):").split(",")

    def _login(self):
        self.driver.get(self.login_url)
        # 顯示等待

        # 隱式等待
        WebDriverWait(self.driver, 1000).until(
            EC.url_to_be(self.init_my_url)
        )
        print("登陸成功")

    def _order_ticket(self):
        # 1.跳轉到查餘票的介面
        self.driver.get(self.search_url)
        # 2.等待出發地是否輸入正確
        WebDriverWait(self.driver, 1000).until(
            EC.text_to_be_present_in_element_value((By.ID, "fromStationText"), self.from_station)
        )
        # 3.等待目的地是否輸入正確
        WebDriverWait(self.driver, 1000).until(
            EC.text_to_be_present_in_element_value((By.ID, "toStationText"), self.to_station)
        )
        # 4.等待出發日期是否輸入正確
        WebDriverWait(self.driver, 1000).until(
            EC.text_to_be_present_in_element_value((By.ID, "train_date"), self.depart_time)
        )
        # 5.等待查詢日期是否可用
        WebDriverWait(self.driver, 1000).until(
            EC.element_to_be_clickable((By.ID, "query_ticket"))
        )
        # 6.如果能夠被點選了,那麼就找到這個查詢按鈕,執行點選事件
        searchBtn = self.driver.find_element_by_id("query_ticket")
        searchBtn.click()

    def run(self):
        self.wait_input()
        self._login()
        self._order_ticket()


if __name__ == '__main__':
    spider = Qiangpiao()
    spider.run()