1. 程式人生 > >python+selenium實現自動搶票

python+selenium實現自動搶票

使用說明

程式執行開始,需要輸入出發地,目的地,出發時間,乘客資訊,車次;乘客資訊和車次可以輸入多個
剛剛開始學習爬蟲,selenium僅僅是解放了雙手,執行效率不是很高;
程式執行時會開啟chrome瀏覽器,因為使用的是chrome的瀏覽器驅動;

相關文件

https://selenium-python.readthedocs.io/installation.html#introduction

程式碼示例


# encoding: utf-8

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


class Qiangpiao(object):

    def __init__(self):
        driver_path = "E:\py_pachong\chromedriver.exe"
        # 瀏覽器驅動
        self.drive = webdriver.Chrome(executable_path=driver_path)
        # 登陸連結
        self.login_url = "https://kyfw.12306.cn/otn/login/init"
        # 登陸後的連結
        self.initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306"
        # 查詢頁面
        self.search_url = "https://kyfw.12306.cn/otn/leftTicket/init"
        # 乘車人頁面
        self.passenger_url = "https://kyfw.12306.cn/otn/confirmPassenger/initDc"

    def wait_input(self):
        """
        主要用於頁面稽核;
        當輸入出發地,目的地,乘車時間後,會自動出發查詢submit
        :return:
        """
        self.from_station = input("出發地:")
        self.to_station = input("目的地:")
        self.depart_time = input("出發時間:")
        self.passengers = input("乘客姓名:").split(",")
        self.trains = input("車次:").split(",")

    def _login(self):
        """
        登陸驗證,登陸成功後會跳轉到 self.initmy_url
        :return:
        """
        self.drive.get(self.login_url)
        WebDriverWait(self.drive, 1000).until(
            EC.url_to_be(self.initmy_url)
        )
        print('登入成功')

    def _order_ticket(self):
        """
        只實現了在無票的情況下去刷票
        最關鍵的是等待驗證  WebDriverWait
        :return:
        """
        self.drive.get(self.search_url)
        WebDriverWait(self.drive, 1000).until(
            EC.text_to_be_present_in_element_value((By.ID, "fromStationText"), self.from_station)
        )

        WebDriverWait(self.drive, 1000).until(
            EC.text_to_be_present_in_element_value((By.ID, "toStationText"), self.to_station)
        )

        WebDriverWait(self.drive, 1000).until(
            EC.text_to_be_present_in_element_value((By.ID, "train_date"), self.depart_time)
        )

        WebDriverWait(self.drive, 10000).until(
            EC.element_to_be_clickable((By.ID, "query_ticket"))
        )

        searchBtn = self.drive.find_element_by_id("query_ticket")
        searchBtn.click()

        WebDriverWait(self.drive, 1000).until(
            EC.presence_of_element_located((By.XPATH, ".//tbody[@id='queryLeftTable']/tr"))
        )

        # find_elements_by_xpath 返回的是一個列表
        # find_element_by_xpath 返回的是一個元素
        tr_list = self.drive.find_elements_by_xpath(".//tbody[@id='queryLeftTable']/tr[not(@datatran)]")

        for tr in tr_list:
            train_num = tr.find_element_by_class_name("number").text
            # print(train_num)
            if train_num in self.trains:
                left_ticket_td = tr.find_element_by_xpath(".//td[4]").text
                num = 1
                while left_ticket_td == "無":
                    print("暫時無票,正在重新整理")
                    time.sleep(2)
                    searchBtn.click()
                    num += 1
                    print("搶票%s次" % num)

                    if left_ticket_td != "無":
                        print(train_num + "有票")
                        oderBtn = tr.find_element_by_xpath(".//td[13]/a")
                        oderBtn.click()

                        WebDriverWait(self.drive, 1000).until(
                            EC.url_to_be(self.passenger_url)
                        )

                        WebDriverWait(self.drive, 1000).until(
                            EC.presence_of_element_located((By.XPATH, ".//ul[@id='normal_passenger_id']/li"))
                        )

                        passenger_labels = self.drive.find_elements_by_xpath(
                            ".//ul[@id='normal_passenger_id']/li/label")
                        for passenger_label in passenger_labels:
                            name = passenger_label.text
                            if name in self.passengers:
                                passenger_label.click()

                        submitBtn = self.drive.find_element_by_id("submitOrder_id")
                        submitBtn.click()

                        WebDriverWait(self.drive, 1000).until(
                            EC.presence_of_element_located((By.CLASS_NAME, "dhtmlx_wins_body_outer"))
                        )

                        WebDriverWait(self.drive, 1000).until(
                            EC.presence_of_element_located((By.ID, "qr_submit_id"))
                        )

                        qr_submit = self.drive.find_element_by_id("qr_submit_id")
                        qr_submit.click()

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


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