基于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()

 

你可能感兴趣的:(爬虫,python)