最新12306搶票爬蟲

專注的阿熊發表於2022-01-21

import time

import datetime

from selenium import webdriver

from selenium.webdriver.common.action_chains import ActionChains

from selenium.webdriver.common.by import By

from selenium.webdriver.common.keys import Keys

from selenium.webdriver.support.wait import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

class Qiangpiao():

     def __init__(self,from_station,to_station,depart_time,train_num,passenger):

         self.login_url = '

         self.init_my_url = '

         self.order_url = '

         # input(" 出發地: ")

         self.from_station = from_station

         # input(" 目的地: ")

         self.to_station = to_station

         # 時間格式必須是 M-d 的方式

         # input(" 出發時間 ( 格式必須是 M-d 的方式 ) ")

         self.depart_time = depart_time

         # input(" 列車號: ")

         self.train_num = train_num

         self.passenger = passenger

         # 獲取當前月份

         self.now_month = datetime.date.today().month

         self.leave_month = int(self.depart_time.split('-')[0])

         self.leave_day = int(self.depart_time.split('-')[1])

         self.driver = webdriver.Chrome()

     def _login(self):

         self.driver.get(self.login_url)

         # 視窗最大化

         #self.driver.maximize_window()

         # 設定視窗大小

         self.driver.set_window_size(1300,800)

         #print(' 調整前尺寸 :', self.driver.get_window_size())

         # 顯式等待

         # 這裡進行手動登入,可以掃碼,也可以輸入賬號密碼點選登入

         WebDriverWait(self.driver,1000).until(EC.url_to_be(self.init_my_url))

         print(' 登入成功! ')

     def _pop_window(self):

         time.sleep(1)

         self.driver.find_element_by_xpath('//*[@class="dzp-confirm"]/div[2]/div[3]/a').click()

     def _enter_order_ticket(self):

         action = ActionChains(self.driver)   # 例項化一個動作鏈物件

         element = self.driver.find_element_by_link_text(' 車票 ')

         # 滑鼠移動到 ' 車票 ' 元素上的中心點

         action.move_to_element(element).perform()

         # 點選 ' 單程 '

         self.driver.find_element_by_xpath('//*[@id="J-chepiao"]/div/div[1]/ul/li[1]/a').click()

         # 消除第二次彈窗

         self.driver.find_element_by_link_text(' 確認 ').click()

     def _search_ticket(self):

         # 出發地輸入

         self.driver.find_element_by_id("fromStationText").click()

         self.driver.find_element_by_id("fromStationText").send_keys(self.from_station)

         self.driver.find_element_by_id("fromStationText").send_keys(Keys.ENTER)

         # 目的地輸入

         self.driver.find_element_by_id("toStationText").click()

         self.driver.find_element_by_id("toStationText").send_keys(self.to_station)

         self.driver.find_element_by_id("toStationText").send_keys(Keys.ENTER)

         # 出發日期輸入

         self.driver.find_element_by_id("date_icon_1").click()

         if self.leave_month == self.now_month:

             xpath_str = f"/html/body/div[37]/div[1]/div[2]/div[{self.leave_day}]"

             if EC.element_to_be_clickable((By.XPATH, xpath_str)):

                 self.driver.find_element_by_xpath(xpath_str).click()

             else:

                 print(" 當前日期未到或已過售票日期,無法購票! ")

         elif self.leave_month == self.now_month + 1:

             xpath_str = f"/html/body/div[37]/div[2]/div[2]/div[{self.leave_day}]"

             if EC.element_to_be_clickable((By.XPATH, xpath_str)):

                 self.driver.find_element_by_xpath(xpath_str).click()

             else:

                 print(" 當前日期未到或已過售票日期,無法購票! ")

         else:

             print(" 月份超前一個月以上,無法購票! ")

         # 等待查詢按鈕是否可用

WebDriverWait(self.driver,1000).until(EC.element_to_be_clickable((By.ID,"query_ticket")))

         # 執行點選事件

         search_btn = self.driver.find_element_by_id("query_ticket")

         search_btn.click()

         # 等待查票資訊載入

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

     def _order_ticket(self):

         train_num_list = []  # 列車號列表

         train_num_ele_list = self.driver.find_elements_by_xpath('//tr/td[1]/div/div[1]/div/a')  # 列車號元素列表

         for t in train_num_ele_list:    # 外匯跟單gendan5.com 遍歷列車號元素列表,並把列車號新增到列車號列表

             train_num_list.append(t.text)

         tr_list = self.driver.find_elements_by_xpath('//*[@id="queryLeftTable"]/tr[not(@datatran)]')  # 每一列列車整行資訊列表,列車號元素是 tr 的子元素

         if self.train_num in train_num_list:

             for tr in tr_list:

                 train_num = tr.find_element_by_xpath("./td[1]/div/div[1]/div/a").text  # 取出元素 tr 裡的列車號

                 if self.train_num == train_num:

                     # 動車二等座餘票資訊

                     text_1 = tr.find_element_by_xpath("./td[4]").text

                     # 火車二等座餘票資訊

                     text_2 = tr.find_element_by_xpath("./td[8]").text

                     if (text_1 == " " or text_1.isdigit()) or (text_2 == " " or text_2.isdigit()):

                         # 點選預訂按鈕

                         order_btn = tr.find_element_by_class_name("btn72")

                         order_btn.click()

                         # 等待訂票頁面

                         WebDriverWait(self.driver,1000).until(EC.url_to_be(self.order_url))

                         # 選定乘車人

self.driver.find_element_by_xpath(f'//*[@id="normal_passenger_id"]/li/label[contains(text(),"{self.passenger}")]').click()

                         # 如果乘客是學生,對提示點選確定

                         if EC.presence_of_element_located((By.XPATH, '//div[@id="dialog_xsertcj"]')):

                             self.driver.find_element_by_id('dialog_xsertcj_ok').click()

                             # 提交訂單

                             self.driver.find_element_by_id('submitOrder_id').click()

                             time.sleep(2)

                             # 點選確認訂單

                             self.driver.find_element_by_id('qr_submit_id').click()

                         else:

                             # 提交訂單

                             self.driver.find_element_by_id('submitOrder_id').click()

                             time.sleep(2)

                             # 點選確認

                             self.driver.find_element_by_id('qr_submit_id').click()

                             print(" 購票成功! ")

                             break

                     else:

                         print(" 二等座無票! ")

         else:

             print(" 無此列車! ")

     def run(self):

         # 登入

         self._login()

         # 消除登入後(第一次)的彈窗

         self._pop_window()

         # 進入購票頁面

         self._enter_order_ticket()

         # 查票

         self._search_ticket()

         # 訂票

         self._order_ticket()

         # 關閉瀏覽器

         time.sleep(6)

         self.driver.quit()

if __name__ == '__main__':

     qiangpiao = Qiangpiao(" 蘭州 "," 烏魯木齊 ","8-6","D55"," 小紅 ")

     qiangpiao.run()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2853454/,如需轉載,請註明出處,否則將追究法律責任。

相關文章