-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuy_ticket.py
executable file
·427 lines (348 loc) · 12.4 KB
/
buy_ticket.py
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#!/usr/bin/python3.6
# coding=UTF-8
import os
import sys
import argparse
import datetime
from inspect import getframeinfo, stack
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from time import sleep
def die(msg,exitcode=1):
sys.stderr.write('{} {}:{} ERROR: {}\n'.format(
datetime.datetime.now(),
caller.filename,
caller.lineno,
msg
)
)
sys.exit(exitcode)
def is_date(msg):
try:
datetime.datetime.strptime(msg, '%d.%m.%Y')
except ValueError:
die('Wrong date option!',2)
def is_time(msg):
try:
datetime.datetime.strptime(msg, '%H:%M')
except ValueError:
die('Wrong time option!',3)
def log_info(msg):
caller = getframeinfo(stack()[1][0])
sys.stdout.write('{} {}:{} INFO: {}\n'.format(
datetime.datetime.now(),
caller.filename,
caller.lineno,
msg
)
)
def load_user_credentials(filename):
import imp
f = open(filename)
credentials = imp.load_source('person', '', f)
f.close()
return credentials
def buy_ticket(args):
# FIREFOX DESTINATION FOLDER
folder = os.path.dirname(os.path.realpath(__file__))
# FIREFOX OPTIONS
options = Options();
options.headless = args.headless
# FIREFOX PROFILE
profile = FirefoxProfile()
profile.set_preference('browser.download.folderList',2);
profile.set_preference('browser.download.manager.showWhenStarting', False);
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream,application/vnd.ms-excel');
profile.set_preference('browser.download.dir',str(folder));
log_info('FirefoxProfile: "browser.download.dir" = "{}"'.format(str(folder)))
# Launch Firefox web browser.
driver = webdriver.Firefox(options=options, firefox_profile=profile)
# Use full screen mode.
# driver.maximize_window()
# Logging information
log_info('Opened {} (version {})'.format(
driver.capabilities['browserName'],
driver.capabilities['browserVersion']
)
)
# Sets a sticky timeout to implicitly wait for an element to be found, or a command to complete.
driver.implicitly_wait(30)
# Load page 'Vyhľadanie spojenia'
driver.get('https://ikvc.slovakrail.sk/esales/search')
# Info
log_info('Loading page "Vyhľadanie spojenia"')
try:
delay = 30 # wait seconds for web page to load, added more second
WebDriverWait(driver, delay).until(
EC.presence_of_all_elements_located(
(By.ID, 'searchPanel')
)
)
# Logging information
log_info('Loaded page "Vyhľadanie spojenia"')
except TimeoutException:
log_info('Loading took too much time.')
log_info('Closed {} (version {}).'.format(
driver.capabilities['browserName'],
driver.capabilities['browserVersion']
)
)
driver.close()
die('Page loading failure.',1)
sleep(1)
# Info
log_info('Page title is "{}".'.format(driver.title))
# Check if 'ZSSK' is in the page title
assert 'ZSSK' in driver.title
# FROM
elem_city_from = driver.find_element_by_id('fromInput')
elem_city_from.clear()
elem_city_from.send_keys(args.departure)
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/div/div/form/div[1]/div/div[1]/div[1]/div[1]/ul/li/a'
).click
log_info('Filling "Odkiaľ" in "Vyhľadanie spojenia" with "{}".'.format(args.departure))
sleep(0.5)
# TO
elem_city_to = driver.find_element_by_id('toInput')
elem_city_to.clear()
elem_city_to.send_keys(args.arrival)
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/div/div/form/div[1]/div/div[1]/div[1]/div[3]/ul/li/a'
).click
log_info('Filling "Kam" in "Vyhľadanie spojenia" with "{}".'.format(args.arrival))
sleep(0.5)
# DATE
elem_date = driver.find_element_by_id('departDate')
elem_date.clear()
elem_date.send_keys(args.date)
driver.find_element_by_xpath('//html').click();
log_info('Filling "Dátum cesty tam" in "Vyhľadanie spojenia" with "{}".'.format(args.date))
sleep(0.5)
# TIME
elem_time = driver.find_element_by_id('departTime')
elem_time.clear()
elem_time.send_keys(args.time)
driver.find_element_by_xpath('//html').click();
log_info('Filling "Odchod" in "Vyhľadanie spojenia" with "{}".'.format(args.time))
sleep(0.5)
log_info('Filled train credentials in "Vyhľadanie spojenia".')
# CONFIRM
driver.find_element_by_id('actionSearchConnectionButton').click()
log_info('Clicked on "Vyhľadať spojenie".')
sleep(2)
# CLICK ON FIRST
driver.find_element_by_css_selector(
'div.connection-group:nth-child(2) > div:nth-child(1)'
).click()
log_info('Clicked on first train.')
sleep(1)
# BUY TICKET
driver.find_element_by_xpath(
'//*[@id="dayGroupLoop:0:eSalesConnectionLoop:0:j_idt302"]'
).click()
log_info('Clicked on "Kúpiť lístok".')
sleep(1)
# PASSENGER TYPE SELECTION
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/span/div/div[1]/form/div/div/div/div/div/div/div[1]/div[1]/div/div/div/div/a[1]/span[2]'
).click()
log_info('Choosing passenger type.')
sleep(1)
# JUNIOR SELECTION
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/span/div/div[1]/form/div/div/div/div/div/div/div[1]/div[1]/div/div/div[1]/div/a[1]/ul/li[3]'
).click()
log_info('Selected "Mladý (16 - 25 r.)".')
sleep(1)
# DISCOUNT SELECTION
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/span/div/div[1]/form/div/div/div/div/div/div/div[1]/div[1]/div/div/div/div/a[2]/span[2]'
).click()
log_info('Choosing card type.')
sleep(1)
# CARD SELECTION
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/span/div/div[1]/form/div/div/div/div/div/div/div[1]/div[1]/div/div/div[1]/div/a[2]/ul/li[2]'
).click()
log_info('Selected "Preukaz pre žiaka/Študenta".')
sleep(1)
# ENABLED OPTION FOR FREE TICKET
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/span/div/div[1]/form/div/div/div/div/div/div/div[1]/div[1]/div/div/div[2]/div/div/label'
).click()
log_info('Checkbox enabled for "Nárok na bezplatnú prepravu".')
sleep(1)
# CONTINUE
driver.find_element_by_xpath(
'//*[@id="actionIndividualContinue"]'
).click()
log_info('Clicked on "Pokračovať" at "Voľba cestujúcich".')
sleep(3)
# CONTINUE
driver.find_element_by_xpath(
'//*[@id="ticketsForm:connection-offer:final-price:j_idt198"]'
).click()
log_info('Clicked on "Pokračovať" at "Voľba cestovného lístka".')
sleep(1)
# CONTINUE
driver.find_element_by_xpath(
'//*[@id="ticketsForm:j_idt97"]'
).click()
log_info('Clicked on "Pokračovať" at "Doplnkové služby".')
sleep(1)
# CONTINUE
driver.find_element_by_xpath(
'//*[@id="cartForm:j_idt284"]'
).click()
log_info('Clicked on "Pokračovať" at "Obsah košíka (1)".')
sleep(1)
# LOAD PERSONAL INFORMATION
person = load_user_credentials('person.txt')
# FILL EMAIL
email = driver.find_element_by_id('email')
email.clear()
email.send_keys(person.email)
log_info('Filling "Váš e-mail" at "Osobné údaje (2)".')
# FILL NAME
name = driver.find_element_by_id('cartItemLoop:0:connectionPersonal:passengerLoop:0:firstname')
name.clear()
name.send_keys(person.name)
log_info('Filling "Meno" at "Osobné údaje (2)".')
# FILL SURNAME
surname = driver.find_element_by_id('cartItemLoop:0:connectionPersonal:passengerLoop:0:lastname')
surname.clear()
surname.send_keys(person.surname)
log_info('Filling "Priezvisko" at "Osobné údaje (2)".')
# FILL REGISTRATION NUMBER
card_number = driver.find_element_by_id('cartItemLoop:0:connectionPersonal:passengerLoop:0:cislo-registracie-p1')
card_number.clear()
card_number.send_keys(person.train_card)
log_info('Filling "Číslo registrácie:" at "Osobné údaje (2)".')
log_info('All personal informations filled at "Osobné údaje (2)".')
# CONTINUE
driver.find_element_by_xpath(
'//*[@id="j_idt177"]'
).click()
log_info('Clicked on "Pokračovať" at "Osobné údaje (2)".')
sleep(1)
# I AGREE WITH THE TERMS AND CONDITIONS
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/div[2]/div/form/div/div/div[1]/div/div/div/label'
).click()
log_info('Checkbox enabled for "Súhlasím s obchodnými podmienkami " at "Výber platby (3)".')
sleep(1)
# CONTINUE
driver.find_element_by_xpath(
'//*[@id="j_idt107"]'
).click()
log_info('Clicked on "Pokračovať" at "Výber platby (3)".')
sleep(1)
# PAY
driver.find_element_by_xpath(
'//*[@id="cartForm:j_idt240"]'
).click()
log_info('Clicked on "Zaplatiť" at "Súhrn (4)".')
sleep(1)
"""
TODO
# DOWNLOAD PDF
log_info('DOWNLOAD: Clicked on "Uložiť lístok".')
driver.find_element_by_xpath(
'/html/body/div[1]/div/div[2]/div[3]/div[2]/div/form/div/div/div[3]/div[1]/a'
).click()
log_info('DOWNLOAD: PDF downloaded to "{}".'.format(str(folder)))
"""
# Waiting 10 seconds
log_info('Waiting 10 seconds before closing {} (version {}).'.format(
driver.capabilities['browserName'],
driver.capabilities['browserVersion']
)
)
sleep(10)
# Close the web browser (Firefox).
driver.close()
# Info
log_info('Closed {} (version {}).'.format(
driver.capabilities['browserName'],
driver.capabilities['browserVersion']
)
)
def main():
# Argument parser
parser = argparse.ArgumentParser(
description = (
'Automated webticket buying for "slovakrail.sk". You have to specify\n'
'departure and arrival stations, date and time in an exact form, like\n'
'it is on the website of the "slovakrail.sk".\n'
),
epilog = (
'EXAMPLES\n'
' python3.6 buy_ticket -h\n'
' python3.6 buy_ticket.py -D "Bratislava hl.st." -A "Kúty" -t "05:16" -d "18.03.2019"\n'
' python3.6 buy_ticket.py -D "Bratislava hl.st." -A "Kúty" -t "05:16" -d "18.03.2019" -H\n'
),
formatter_class = argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'--departure',
'-D',
help='Exact departure station.'
)
parser.add_argument(
'--arrival',
'-A',
help='Exact arrival station.'
)
parser.add_argument(
'--time',
'-t',
help='Exact departure time in format: HH:MM.'
)
parser.add_argument(
'--date',
'-d',
help='Exact departure date in format: DD.MM.YYYY.'
)
parser.add_argument(
'-H',
'--headless',
action='store_true',
help='Run browser in a headless mode.'
)
# Argument parsing.
args = parser.parse_args()
# Info
log_info('Running {}'.format(str(__file__)))
# Date check
is_date(args.date)
log_info('DATE = {}'.format(args.date))
# Time check
is_time(args.time)
log_info('TIME = {}'.format(args.time))
# Departure destination check
if isinstance(args.departure, str):
log_info('DEPARTURE = {}'.format(args.departure))
else:
die('Wrong departure option!',4)
# Arrival destination check
if isinstance(args.arrival, str):
log_info('ARRIVAL = {}'.format(args.arrival))
else:
die('Wrong arrival option!',5)
# Headless browser mode
log_info('HEADLESS = {}'.format(args.headless))
# Buy ticket
buy_ticket(args)
# Info
log_info("Terminating {}".format(str(__file__)))
# Terminate the program with exit status 0.
sys.exit(0)
if __name__ == '__main__':
main()