-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path12306_python.py
More file actions
212 lines (200 loc) · 10.9 KB
/
Copy path12306_python.py
File metadata and controls
212 lines (200 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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 = 'https://kyfw.12306.cn/otn/resources/login.html'
self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'
self.order_url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
# 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):
try:
# 等待元素可点击
element = WebDriverWait(self.driver, 3).until(
EC.element_to_be_clickable((By.XPATH, '//*[@class="dzp-confirm"]/div[2]/div[3]/a'))
)
element.click()
except Exception as e:
print(f"Error occurred while clicking the pop-up window: {e}")
def _enter_order_ticket(self):
action = ActionChains(self.driver) # 实例化一个动作链对象
# element = self.driver.find_element_by_link_text('车票')
element = self.driver.find_element(By.LINK_TEXT, '车票')
# 鼠标移动到 '车票' 元素上的中心点
action.move_to_element(element).perform()
# 点击'单程'
self.driver.find_element(By.XPATH, '//*[@id="megamenu-3"]/div[1]/ul/li[1]/a').click()
# 消除第二次弹窗
#self.driver.find_element(By.LINK_TEXT, '确认').click()
def _search_ticket(self):
#出发地输入 //*[@id="fromStationText"]
wait = WebDriverWait(self.driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, "fromStationText")))
element.click()
self.driver.find_element(By.ID,"fromStationText").send_keys(self.from_station)
self.driver.find_element(By.ID,"fromStationText").send_keys(Keys.ENTER)
#目的地输入 //*[@id="toStationText"]
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)
#出发日期输入 //*[@id="train_date"]
self.driver.find_element(By.ID,"train_date").click()
self.driver.find_element(By.ID, "train_date").clear()
self.driver.find_element(By.ID,"train_date").send_keys(self.depart_time)
self.driver.find_element(By.ID,"train_date").send_keys(Keys.ENTER)
# if self.leave_month == self.now_month: #//*[@id="train_date"]
# xpath_str = f"/html/body/div[38]/div[1]/div[2]/div[16]/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[38]/div[1]/div[2]/div[16]/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("月份超前一个月以上,无法购票!")
#等待查询按钮是否可用 //*[@id="query_ticket"]
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: # 遍历列车号元素列表,并把列车号添加到列车号列表
# 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: # //*[@id="train_num_0"]
# 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 _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: # 遍历列车号元素列表,并把列车号添加到列车号列表
train_num_list.append(t.text)
#print(train_num_list)
#tr_list = self.driver.find_elements(By.XPATH, '//*[@id="queryLeftTable"]/tr[not(@datatran)]') #每一列列车整行信息列表,列车号元素是tr的子元素
if self.train_num in train_num_list:
tr_list = self.driver.find_elements(By.XPATH, '//*[@id="queryLeftTable"]/tr[not(@datatran)]')
for tr in tr_list:
print(tr.get_attribute("outerHTML"))
WebDriverWait(tr, 20).until(
EC.presence_of_element_located((By.XPATH, "./td[1]/div/div[1]/div/a"))
)
train_num = tr.find_element(By.XPATH, "./td[1]/div/div[1]/div/a").text
print(f"列车号: {train_num}")
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()
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("合肥南","淮南","2025-01-24","G9284","姚玮烨")
qiangpiao.run()