forked from Gilg4mesh/tixcraft_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchrome_tixcraft.py
11090 lines (9389 loc) · 413 KB
/
chrome_tixcraft.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#encoding=utf-8
#執行方式:python chrome_tixcraft.py 或 python3 chrome_tixcraft.py
#import jieba
#from DrissionPage import ChromiumPage
#import nodriver as uc
import argparse
import base64
import json
import logging
import os
import platform
import random
import ssl
import subprocess
import sys
import threading
import time
import warnings
import webbrowser
from datetime import datetime
import chromedriver_autoinstaller_max
import requests
from selenium import webdriver
from selenium.common.exceptions import (NoAlertPresentException,
NoSuchWindowException,
UnexpectedAlertPresentException,
WebDriverException)
from selenium.webdriver.chrome.service import Service
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 import expected_conditions as EC
from selenium.webdriver.support.ui import Select, WebDriverWait
from urllib3.exceptions import InsecureRequestWarning
import util
from NonBrowser import NonBrowser
try:
import ddddocr
except Exception as exc:
print(exc)
pass
CONST_APP_VERSION = "MaxBot (2024.04.10)"
CONST_MAXBOT_ANSWER_ONLINE_FILE = "MAXBOT_ONLINE_ANSWER.txt"
CONST_MAXBOT_CONFIG_FILE = "settings.json"
CONST_MAXBOT_EXTENSION_NAME = "Maxbotplus_1.0.0"
CONST_MAXBOT_INT28_FILE = "MAXBOT_INT28_IDLE.txt"
CONST_MAXBOT_LAST_URL_FILE = "MAXBOT_LAST_URL.txt"
CONST_MAXBOT_QUESTION_FILE = "MAXBOT_QUESTION.txt"
CONST_MAXBLOCK_EXTENSION_NAME = "Maxblockplus_1.0.0"
CONST_MAXBLOCK_EXTENSION_FILTER =[
"*.doubleclick.net/*",
"*.googlesyndication.com/*",
"*.ssp.hinet.net/*",
"*a.amnet.tw/*",
"*adx.c.appier.net/*",
"*cdn.cookielaw.org/*",
"*cdnjs.cloudflare.com/ajax/libs/clipboard.js/*",
"*clarity.ms/*",
"*cloudfront.com/*",
"*cms.analytics.yahoo.com/*",
"*e2elog.fetnet.net/*",
"*fundingchoicesmessages.google.com/*",
"*ghtinc.com/*",
"*google-analytics.com/*",
"*googletagmanager.com/*",
"*googletagservices.com/*",
"*img.uniicreative.com/*",
"*lndata.com/*",
"*match.adsrvr.org/*",
"*onead.onevision.com.tw/*",
"*play.google.com/log?*",
"*popin.cc/*",
"*rollbar.com/*",
"*sb.scorecardresearch.com/*",
"*tagtoo.co/*",
"*ticketmaster.sg/js/adblock*",
"*ticketmaster.sg/js/adblock.js*",
"*tixcraft.com/js/analytics.js*",
"*tixcraft.com/js/common.js*",
"*tixcraft.com/js/custom.js*",
"*treasuredata.com/*",
"*www.youtube.com/youtubei/v1/player/heartbeat*",
]
CONST_CHROME_VERSION_NOT_MATCH_EN="Please download the WebDriver version to match your browser version."
CONST_CHROME_VERSION_NOT_MATCH_TW="請下載與您瀏覽器相同版本的WebDriver版本,或更新您的瀏覽器版本。"
CONST_CHROME_DRIVER_WEBSITE = 'https://chromedriver.chromium.org/'
CONST_CITYLINE_SIGN_IN_URL = "https://www.cityline.com/Login.html?targetUrl=https%3A%2F%2Fwww.cityline.com%2FEvents.html"
CONST_FAMI_SIGN_IN_URL = "https://www.famiticket.com.tw/Home/User/SignIn"
CONST_HKTICKETING_SIGN_IN_URL = "https://premier.hkticketing.com/Secure/ShowLogin.aspx"
CONST_KHAM_SIGN_IN_URL = "https://kham.com.tw/application/UTK13/UTK1306_.aspx"
CONST_KKTIX_SIGN_IN_URL = "https://kktix.com/users/sign_in?back_to=%s"
CONST_TICKET_SIGN_IN_URL = "https://ticket.com.tw/application/utk13/utk1306_.aspx"
CONST_URBTIX_SIGN_IN_URL = "https://www.urbtix.hk/member-login"
CONST_FROM_TOP_TO_BOTTOM = "from top to bottom"
CONST_FROM_BOTTOM_TO_TOP = "from bottom to top"
CONST_CENTER = "center"
CONST_RANDOM = "random"
CONT_STRING_1_SEATS_REMAINING = ['@1 seat(s) remaining','剩餘 1@','@1 席残り']
CONST_OCR_CAPTCH_IMAGE_SOURCE_NON_BROWSER = "NonBrowser"
CONST_OCR_CAPTCH_IMAGE_SOURCE_CANVAS = "canvas"
CONST_WEBDRIVER_TYPE_SELENIUM = "selenium"
CONST_WEBDRIVER_TYPE_UC = "undetected_chromedriver"
CONST_WEBDRIVER_TYPE_DP = "DrissionPage"
CONST_WEBDRIVER_TYPE_NODRIVER = "nodriver"
CONST_CHROME_FAMILY = ["chrome","edge","brave"]
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
CONST_PREFS_DICT = {
"credentials_enable_service": False,
"in_product_help.snoozed_feature.IPH_LiveCaption.is_dismissed": True,
"in_product_help.snoozed_feature.IPH_LiveCaption.last_dismissed_by": 4,
"media_router.show_cast_sessions_started_by_other_devices.enabled": False,
"net.network_prediction_options": 3,
"privacy_guide.viewed": True,
"profile.default_content_setting_values.notifications": 2,
"profile.default_content_setting_values.sound": 2,
"profile.name": CONST_APP_VERSION,
"profile.password_manager_enabled": False,
"safebrowsing.enabled":False,
"safebrowsing.enhanced":False,
"sync.autofill_wallet_import_enabled_migrated":False,
"translate":{"enabled": False}}
warnings.simplefilter('ignore',InsecureRequestWarning)
ssl._create_default_https_context = ssl._create_unverified_context
logging.basicConfig()
logger = logging.getLogger('logger')
def get_config_dict(args):
app_root = util.get_app_root()
config_filepath = os.path.join(app_root, CONST_MAXBOT_CONFIG_FILE)
# allow assign config by command line.
if not args.input is None:
if len(args.input) > 0:
config_filepath = args.input
config_dict = None
if os.path.isfile(config_filepath):
# start to overwrite config settings.
with open(config_filepath) as json_data:
config_dict = json.load(json_data)
if not args.headless is None:
config_dict["advanced"]["headless"] = util.t_or_f(args.headless)
if not args.homepage is None:
if len(args.homepage) > 0:
config_dict["homepage"] = args.homepage
if not args.ticket_number is None:
if args.ticket_number > 0:
config_dict["ticket_number"] = args.ticket_number
if not args.browser is None:
if len(args.browser) > 0:
config_dict["browser"] = args.browser
if not args.tixcraft_sid is None:
if len(args.tixcraft_sid) > 0:
config_dict["advanced"]["tixcraft_sid"] = args.tixcraft_sid
if not args.ibonqware is None:
if len(args.ibonqware) > 0:
config_dict["advanced"]["ibonqware"] = args.ibonqware
if not args.kktix_account is None:
if len(args.kktix_account) > 0:
config_dict["advanced"]["kktix_account"] = args.kktix_account
if not args.kktix_password is None:
if len(args.kktix_password) > 0:
config_dict["advanced"]["kktix_password_plaintext"] = args.kktix_password
if not args.proxy_server is None:
if len(args.proxy_server) > 2:
config_dict["advanced"]["proxy_server_port"] = args.proxy_server
if not args.window_size is None:
if len(args.window_size) > 2:
config_dict["advanced"]["window_size"] = args.window_size
# special case for headless to enable away from keyboard mode.
is_headless_enable_ocr = False
if config_dict["advanced"]["headless"]:
# for tixcraft headless.
#print("If you are runnig headless mode on tixcraft, you need input your cookie SID.")
if len(config_dict["advanced"]["tixcraft_sid"]) > 1:
is_headless_enable_ocr = True
if is_headless_enable_ocr:
config_dict["ocr_captcha"]["enable"] = True
config_dict["ocr_captcha"]["force_submit"] = True
return config_dict
def write_question_to_file(question_text):
working_dir = os.path.dirname(os.path.realpath(__file__))
target_path = os.path.join(working_dir, CONST_MAXBOT_QUESTION_FILE)
util.write_string_to_file(target_path, question_text)
def write_last_url_to_file(url):
working_dir = os.path.dirname(os.path.realpath(__file__))
target_path = os.path.join(working_dir, CONST_MAXBOT_LAST_URL_FILE)
util.write_string_to_file(target_path, url)
def read_last_url_from_file():
ret = ""
with open(CONST_MAXBOT_LAST_URL_FILE, "r") as text_file:
ret = text_file.readline()
return ret
def get_favoriate_extension_path(webdriver_path, config_dict):
#print("webdriver_path:", webdriver_path)
extension_list = []
extension_list.append(os.path.join(webdriver_path, CONST_MAXBOT_EXTENSION_NAME + ".crx"))
extension_list.append(os.path.join(webdriver_path, CONST_MAXBLOCK_EXTENSION_NAME + ".crx"))
return extension_list
def get_chromedriver_path(webdriver_path):
chromedriver_path = os.path.join(webdriver_path,"chromedriver")
if platform.system().lower()=="windows":
chromedriver_path = os.path.join(webdriver_path,"chromedriver.exe")
return chromedriver_path
def get_chrome_options(webdriver_path, config_dict):
chrome_options = webdriver.ChromeOptions()
if config_dict["browser"]=="edge":
chrome_options = webdriver.EdgeOptions()
if config_dict["browser"]=="safari":
chrome_options = webdriver.SafariOptions()
is_log_performace = False
performace_site = ['ticketplus']
for site in performace_site:
if site in config_dict["homepage"]:
is_log_performace = True
break
if is_log_performace:
if config_dict["browser"] in CONST_CHROME_FAMILY:
chrome_options.set_capability("goog:loggingPrefs",{"performance": "ALL"})
# PS: this is crx version.
extension_list = []
if config_dict["advanced"]["chrome_extension"]:
extension_list = get_favoriate_extension_path(webdriver_path, config_dict)
for ext in extension_list:
if os.path.exists(ext):
chrome_options.add_extension(ext)
if config_dict["advanced"]["headless"]:
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--headless=new')
chrome_options.add_argument("--user-agent=%s" % (USER_AGENT))
chrome_options.add_argument("--disable-animations")
chrome_options.add_argument("--disable-background-networking")
chrome_options.add_argument("--disable-backgrounding-occluded-windows")
chrome_options.add_argument("--disable-bookmark-reordering")
chrome_options.add_argument("--disable-boot-animation")
chrome_options.add_argument("--disable-breakpad")
chrome_options.add_argument("--disable-canvas-aa")
chrome_options.add_argument("--disable-client-side-phishing-detection")
chrome_options.add_argument("--disable-cloud-import")
chrome_options.add_argument("--disable-component-cloud-policy")
chrome_options.add_argument("--disable-component-update")
chrome_options.add_argument("--disable-composited-antialiasing")
chrome_options.add_argument("--disable-default-apps")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-device-discovery-notifications")
chrome_options.add_argument("--disable-dinosaur-easter-egg")
chrome_options.add_argument("--disable-domain-reliability")
chrome_options.add_argument("--disable-features=IsolateOrigins,site-per-process,TranslateUI,PrivacySandboxSettings4")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-logging")
chrome_options.add_argument("--disable-login-animations")
chrome_options.add_argument("--disable-login-screen-apps")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument("--disable-popup-blocking")
chrome_options.add_argument("--disable-print-preview")
chrome_options.add_argument("--disable-renderer-backgrounding")
chrome_options.add_argument("--disable-session-crashed-bubble")
chrome_options.add_argument("--disable-smooth-scrolling")
chrome_options.add_argument("--disable-suggestions-ui")
chrome_options.add_argument("--disable-sync")
chrome_options.add_argument("--disable-translate")
chrome_options.add_argument("--hide-crash-restore-bubble")
chrome_options.add_argument("--lang=zh-TW")
chrome_options.add_argument("--no-default-browser-check")
chrome_options.add_argument("--no-first-run")
chrome_options.add_argument("--no-pings")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--no-service-autorun")
chrome_options.add_argument("--password-store=basic")
# for navigator.webdriver
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
# Deprecated chrome option is ignored: useAutomationExtension
#chrome_options.add_experimental_option('useAutomationExtension', False)
chrome_options.add_experimental_option("prefs", CONST_PREFS_DICT)
if len(config_dict["advanced"]["proxy_server_port"]) > 2:
chrome_options.add_argument('--proxy-server=%s' % config_dict["advanced"]["proxy_server_port"])
if config_dict["browser"]=="brave":
brave_path = util.get_brave_bin_path()
if os.path.exists(brave_path):
chrome_options.binary_location = brave_path
chrome_options.page_load_strategy = 'eager'
#chrome_options.page_load_strategy = 'none'
chrome_options.unhandled_prompt_behavior = "accept"
return chrome_options
def load_chromdriver_normal(config_dict, driver_type):
show_debug_message = True # debug.
show_debug_message = False # online
if config_dict["advanced"]["verbose"]:
show_debug_message = True
driver = None
Root_Dir = util.get_app_root()
webdriver_path = os.path.join(Root_Dir, "webdriver")
chromedriver_path = get_chromedriver_path(webdriver_path)
if not os.path.exists(webdriver_path):
os.mkdir(webdriver_path)
if not os.path.exists(chromedriver_path):
print("WebDriver not exist, try to download to:", webdriver_path)
chromedriver_autoinstaller_max.install(path=webdriver_path, make_version_dir=False)
if not os.path.exists(chromedriver_path):
print("Please download chromedriver and extract zip to webdriver folder from this url:")
print("請下在面的網址下載與你chrome瀏覽器相同版本的chromedriver,解壓縮後放到webdriver目錄裡:")
print(CONST_CHROME_DRIVER_WEBSITE)
else:
chrome_service = Service(chromedriver_path)
chrome_options = get_chrome_options(webdriver_path, config_dict)
try:
driver = webdriver.Chrome(service=chrome_service, options=chrome_options)
except Exception as exc:
error_message = str(exc)
if show_debug_message:
print(exc)
left_part = None
if "Stacktrace:" in error_message:
left_part = error_message.split("Stacktrace:")[0]
print(left_part)
if "This version of ChromeDriver only supports Chrome version" in error_message:
print(CONST_CHROME_VERSION_NOT_MATCH_EN)
print(CONST_CHROME_VERSION_NOT_MATCH_TW)
# remove exist chromedriver, download again.
try:
print("Deleting exist and download ChromeDriver again.")
os.unlink(chromedriver_path)
except Exception as exc2:
print(exc2)
pass
chromedriver_autoinstaller_max.install(path=webdriver_path, make_version_dir=False)
chrome_service = Service(chromedriver_path)
try:
chrome_options = get_chrome_options(webdriver_path, config_dict)
driver = webdriver.Chrome(service=chrome_service, options=chrome_options)
except Exception as exc2:
print("Selenium 4.11.0 Release with Chrome For Testing Browser.")
try:
chrome_options = get_chrome_options(webdriver_path, config_dict)
driver = webdriver.Chrome(service=Service(), options=chrome_options)
except Exception as exc3:
print(exc3)
pass
return driver
def get_uc_options(uc, config_dict, webdriver_path):
options = uc.ChromeOptions()
options.page_load_strategy = 'eager'
#options.page_load_strategy = 'none'
options.unhandled_prompt_behavior = "accept"
#print("strategy", options.page_load_strategy)
is_log_performace = False
performace_site = ['ticketplus']
for site in performace_site:
if site in config_dict["homepage"]:
is_log_performace = True
break
if is_log_performace:
options.set_capability("goog:loggingPrefs",{"performance": "ALL"})
load_extension_path = ""
extension_list = []
if config_dict["advanced"]["chrome_extension"]:
extension_list = get_favoriate_extension_path(webdriver_path, config_dict)
for ext in extension_list:
ext = ext.replace('.crx','')
if os.path.exists(ext):
# sync config.
if CONST_MAXBOT_EXTENSION_NAME in ext:
util.dump_settings_to_maxbot_plus_extension(ext, config_dict, CONST_MAXBOT_CONFIG_FILE)
if CONST_MAXBLOCK_EXTENSION_NAME in ext:
util.dump_settings_to_maxblock_plus_extension(ext, config_dict, CONST_MAXBOT_CONFIG_FILE, CONST_MAXBLOCK_EXTENSION_FILTER)
load_extension_path += ("," + os.path.abspath(ext))
#print("load_extension_path:", load_extension_path)
if len(load_extension_path) > 0:
#print('load-extension:', load_extension_path[1:])
options.add_argument('--load-extension=' + load_extension_path[1:])
if config_dict["advanced"]["headless"]:
#options.add_argument('--headless')
options.add_argument('--headless=new')
options.add_argument("--user-agent=%s" % (USER_AGENT))
options.add_argument("--disable-animations")
options.add_argument("--disable-background-networking")
options.add_argument("--disable-backgrounding-occluded-windows")
options.add_argument("--disable-bookmark-reordering")
options.add_argument("--disable-boot-animation")
options.add_argument("--disable-breakpad")
options.add_argument("--disable-canvas-aa")
options.add_argument("--disable-client-side-phishing-detection")
options.add_argument("--disable-cloud-import")
options.add_argument("--disable-component-cloud-policy")
options.add_argument("--disable-component-update")
options.add_argument("--disable-composited-antialiasing")
options.add_argument("--disable-default-apps")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-device-discovery-notifications")
options.add_argument("--disable-dinosaur-easter-egg")
options.add_argument("--disable-domain-reliability")
options.add_argument("--disable-features=IsolateOrigins,site-per-process,TranslateUI,PrivacySandboxSettings4")
options.add_argument("--disable-infobars")
options.add_argument("--disable-logging")
options.add_argument("--disable-login-animations")
options.add_argument("--disable-login-screen-apps")
options.add_argument("--disable-notifications")
options.add_argument("--disable-popup-blocking")
options.add_argument("--disable-print-preview")
options.add_argument("--disable-renderer-backgrounding")
options.add_argument("--disable-session-crashed-bubble")
options.add_argument("--disable-smooth-scrolling")
options.add_argument("--disable-suggestions-ui")
options.add_argument("--disable-sync")
options.add_argument("--disable-translate")
options.add_argument("--hide-crash-restore-bubble")
options.add_argument("--lang=zh-TW")
options.add_argument("--no-default-browser-check")
options.add_argument("--no-first-run")
options.add_argument("--no-pings")
options.add_argument("--no-sandbox")
options.add_argument("--no-service-autorun")
options.add_argument("--password-store=basic")
options.add_experimental_option("prefs", CONST_PREFS_DICT)
if len(config_dict["advanced"]["proxy_server_port"]) > 2:
options.add_argument('--proxy-server=%s' % config_dict["advanced"]["proxy_server_port"])
if config_dict["browser"]=="brave":
brave_path = util.get_brave_bin_path()
if os.path.exists(brave_path):
options.binary_location = brave_path
return options
def load_chromdriver_uc(config_dict):
import undetected_chromedriver as uc
show_debug_message = True # debug.
show_debug_message = False # online
if config_dict["advanced"]["verbose"]:
show_debug_message = True
Root_Dir = util.get_app_root()
webdriver_path = os.path.join(Root_Dir, "webdriver")
chromedriver_path = get_chromedriver_path(webdriver_path)
if not os.path.exists(webdriver_path):
os.mkdir(webdriver_path)
if not os.path.exists(chromedriver_path):
print("ChromeDriver not exist, try to download to:", webdriver_path)
try:
chromedriver_autoinstaller_max.install(path=webdriver_path, make_version_dir=False)
if not os.path.exists(chromedriver_path):
print("check installed chrome version fail, download last known good version.")
chromedriver_autoinstaller_max.install(path=webdriver_path, make_version_dir=False, detect_installed_version=False)
except Exception as exc:
print(exc)
else:
print("ChromeDriver exist:", chromedriver_path)
driver = None
if os.path.exists(chromedriver_path):
# use chromedriver_autodownload instead of uc auto download.
is_cache_exist = util.clean_uc_exe_cache()
fail_1 = False
lanch_uc_with_path = True
if "macos" in platform.platform().lower():
if "arm64" in platform.platform().lower():
lanch_uc_with_path = False
if lanch_uc_with_path:
try:
options = get_uc_options(uc, config_dict, webdriver_path)
driver = uc.Chrome(driver_executable_path=chromedriver_path, options=options, headless=config_dict["advanced"]["headless"])
except Exception as exc:
print(exc)
error_message = str(exc)
left_part = None
if "Stacktrace:" in error_message:
left_part = error_message.split("Stacktrace:")[0]
print(left_part)
if "This version of ChromeDriver only supports Chrome version" in error_message:
print(CONST_CHROME_VERSION_NOT_MATCH_EN)
print(CONST_CHROME_VERSION_NOT_MATCH_TW)
fail_1 = True
else:
fail_1 = True
fail_2 = False
if fail_1:
try:
options = get_uc_options(uc, config_dict, webdriver_path)
driver = uc.Chrome(options=options)
except Exception as exc:
print(exc)
fail_2 = True
if fail_2:
# remove exist chromedriver, download again.
try:
print("Deleting exist and download ChromeDriver again.")
os.unlink(chromedriver_path)
except Exception as exc2:
print(exc2)
pass
try:
chromedriver_autoinstaller_max.install(path=webdriver_path, make_version_dir=False)
options = get_uc_options(uc, config_dict, webdriver_path)
driver = uc.Chrome(driver_executable_path=chromedriver_path, options=options)
except Exception as exc2:
print(exc2)
pass
else:
print("WebDriver not found at path:", chromedriver_path)
if driver is None:
print('WebDriver object is still None..., try download by uc.')
try:
options = get_uc_options(uc, config_dict, webdriver_path)
driver = uc.Chrome(options=options)
except Exception as exc:
print(exc)
error_message = str(exc)
left_part = None
if "Stacktrace:" in error_message:
left_part = error_message.split("Stacktrace:")[0]
print(left_part)
if "This version of ChromeDriver only supports Chrome version" in error_message:
print(CONST_CHROME_VERSION_NOT_MATCH_EN)
print(CONST_CHROME_VERSION_NOT_MATCH_TW)
pass
if driver is None:
print("create web drive object by undetected_chromedriver fail!")
if os.path.exists(chromedriver_path):
print("Unable to use undetected_chromedriver, ")
print("try to use local chromedriver to launch chrome browser.")
driver_type = "selenium"
driver = load_chromdriver_normal(config_dict, driver_type)
else:
print("建議您自行下載 ChromeDriver 到 webdriver 的資料夾下")
print("you need manually download ChromeDriver to webdriver folder.")
return driver
def close_browser_tabs(driver):
if not driver is None:
try:
window_handles_count = len(driver.window_handles)
if window_handles_count > 1:
driver.switch_to.window(driver.window_handles[1])
driver.close()
driver.switch_to.window(driver.window_handles[0])
except Exception as excSwithFail:
pass
def get_driver_by_config(config_dict):
driver = None
# read config.
homepage = config_dict["homepage"]
# output config:
print("maxbot app version:", CONST_APP_VERSION)
print("python version:", platform.python_version())
print("platform:", platform.platform())
print("homepage:", homepage)
print("browser:", config_dict["browser"])
#print("headless:", config_dict["advanced"]["headless"])
#print("ticket_number:", str(config_dict["ticket_number"]))
#print(config_dict["tixcraft"])
#print("==[advanced config]==")
if config_dict["advanced"]["verbose"]:
print(config_dict["advanced"])
print("webdriver_type:", config_dict["webdriver_type"])
# entry point
if homepage is None:
homepage = ""
Root_Dir = util.get_app_root()
webdriver_path = os.path.join(Root_Dir, "webdriver")
#print("platform.system().lower():", platform.system().lower())
if config_dict["browser"] in ["chrome","brave"]:
# method 6: Selenium Stealth
if config_dict["webdriver_type"] == CONST_WEBDRIVER_TYPE_SELENIUM:
driver = load_chromdriver_normal(config_dict, config_dict["webdriver_type"])
if config_dict["webdriver_type"] == CONST_WEBDRIVER_TYPE_UC:
# method 5: uc
# multiprocessing not work bug.
if platform.system().lower()=="windows":
if hasattr(sys, 'frozen'):
from multiprocessing import freeze_support
freeze_support()
driver = load_chromdriver_uc(config_dict)
if config_dict["webdriver_type"] == CONST_WEBDRIVER_TYPE_DP:
#driver = ChromiumPage()
pass
if config_dict["browser"] == "firefox":
# default os is linux/mac
# download url: https://github.com/mozilla/geckodriver/releases
chromedriver_path = os.path.join(webdriver_path,"geckodriver")
if platform.system().lower()=="windows":
chromedriver_path = os.path.join(webdriver_path,"geckodriver.exe")
if "macos" in platform.platform().lower():
if "arm64" in platform.platform().lower():
chromedriver_path = os.path.join(webdriver_path,"geckodriver_arm")
webdriver_service = Service(chromedriver_path)
driver = None
try:
from selenium.webdriver.firefox.options import Options
options = Options()
if config_dict["advanced"]["headless"]:
options.add_argument('--headless')
#options.add_argument('--headless=new')
if platform.system().lower()=="windows":
binary_path = "C:\\Program Files\\Mozilla Firefox\\firefox.exe"
if not os.path.exists(binary_path):
binary_path = os.path.expanduser('~') + "\\AppData\\Local\\Mozilla Firefox\\firefox.exe"
if not os.path.exists(binary_path):
binary_path = "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"
if not os.path.exists(binary_path):
binary_path = "D:\\Program Files\\Mozilla Firefox\\firefox.exe"
options.binary_location = binary_path
driver = webdriver.Firefox(service=webdriver_service, options=options)
except Exception as exc:
error_message = str(exc)
left_part = None
if "Stacktrace:" in error_message:
left_part = error_message.split("Stacktrace:")[0]
print(left_part)
else:
print(exc)
if config_dict["browser"] == "edge":
# default os is linux/mac
# download url: https://developer.microsoft.com/zh-tw/microsoft-edge/tools/webdriver/
chromedriver_path = os.path.join(webdriver_path,"msedgedriver")
if platform.system().lower()=="windows":
chromedriver_path = os.path.join(webdriver_path,"msedgedriver.exe")
webdriver_service = Service(chromedriver_path)
chrome_options = get_chrome_options(webdriver_path, config_dict)
driver = None
try:
driver = webdriver.Edge(service=webdriver_service, options=chrome_options)
except Exception as exc:
error_message = str(exc)
#print(error_message)
left_part = None
if "Stacktrace:" in error_message:
left_part = error_message.split("Stacktrace:")[0]
print(left_part)
if config_dict["browser"] == "safari":
driver = None
try:
driver = webdriver.Safari()
except Exception as exc:
error_message = str(exc)
#print(error_message)
left_part = None
if "Stacktrace:" in error_message:
left_part = error_message.split("Stacktrace:")[0]
print(left_part)
if driver is None:
print("create web driver object fail @_@;")
else:
try:
NETWORK_BLOCKED_URLS = [
'*.clarity.ms/*',
'*.cloudfront.com/*',
'*.doubleclick.net/*',
'*.lndata.com/*',
'*.rollbar.com/*',
'*.twitter.com/i/*',
'*/adblock.js',
'*/google_ad_block.js',
'*cityline.com/js/others.min.js',
'*anymind360.com/*',
'*cdn.cookielaw.org/*',
'*e2elog.fetnet.net*',
'*fundingchoicesmessages.google.com/*',
'*google-analytics.*',
'*googlesyndication.*',
'*googletagmanager.*',
'*googletagservices.*',
'*img.uniicreative.com/*',
'*platform.twitter.com/*',
'*play.google.com/*',
'*player.youku.*',
'*syndication.twitter.com/*',
'*youtube.com/*',
]
if config_dict["advanced"]["hide_some_image"]:
NETWORK_BLOCKED_URLS.append('*.woff')
NETWORK_BLOCKED_URLS.append('*.woff2')
NETWORK_BLOCKED_URLS.append('*.ttf')
NETWORK_BLOCKED_URLS.append('*.otf')
NETWORK_BLOCKED_URLS.append('*fonts.googleapis.com/earlyaccess/*')
NETWORK_BLOCKED_URLS.append('*/ajax/libs/font-awesome/*')
NETWORK_BLOCKED_URLS.append('*.ico')
NETWORK_BLOCKED_URLS.append('*ticketimg2.azureedge.net/image/ActivityImage/*')
NETWORK_BLOCKED_URLS.append('*static.tixcraft.com/images/activity/*')
NETWORK_BLOCKED_URLS.append('*static.ticketmaster.sg/images/activity/*')
NETWORK_BLOCKED_URLS.append('*static.ticketmaster.com/images/activity/*')
NETWORK_BLOCKED_URLS.append('*ticketimg2.azureedge.net/image/ActivityImage/ActivityImage_*')
NETWORK_BLOCKED_URLS.append('*.azureedge.net/QWARE_TICKET//images/*')
NETWORK_BLOCKED_URLS.append('*static.ticketplus.com.tw/event/*')
#NETWORK_BLOCKED_URLS.append('https://kktix.cc/change_locale?locale=*')
NETWORK_BLOCKED_URLS.append('https://t.kfs.io/assets/logo_*.png')
NETWORK_BLOCKED_URLS.append('https://t.kfs.io/assets/icon-*.png')
NETWORK_BLOCKED_URLS.append('https://t.kfs.io/upload_images/*.jpg')
if config_dict["advanced"]["block_facebook_network"]:
NETWORK_BLOCKED_URLS.append('*facebook.com/*')
NETWORK_BLOCKED_URLS.append('*.fbcdn.net/*')
# Chrome DevTools Protocal
if config_dict["browser"] in CONST_CHROME_FAMILY:
driver.execute_cdp_cmd('Network.setBlockedURLs', {"urls": NETWORK_BLOCKED_URLS})
driver.execute_cdp_cmd('Network.enable', {})
if 'kktix.c' in homepage:
if len(config_dict["advanced"]["kktix_account"])>0:
# for like human.
try:
driver.get(homepage)
time.sleep(5)
except Exception as e:
pass
if not 'https://kktix.com/users/sign_in?' in homepage:
homepage = CONST_KKTIX_SIGN_IN_URL % (homepage)
if 'famiticket.com' in homepage:
if len(config_dict["advanced"]["fami_account"])>0:
homepage = CONST_FAMI_SIGN_IN_URL
if 'kham.com' in homepage:
if len(config_dict["advanced"]["kham_account"])>0:
homepage = CONST_KHAM_SIGN_IN_URL
if 'ticket.com.tw' in homepage:
if len(config_dict["advanced"]["ticket_account"])>0:
homepage = CONST_TICKET_SIGN_IN_URL
if 'urbtix.hk' in homepage:
if len(config_dict["advanced"]["urbtix_account"])>0:
homepage = CONST_URBTIX_SIGN_IN_URL
if 'cityline.com' in homepage:
if len(config_dict["advanced"]["cityline_account"])>0:
homepage = CONST_CITYLINE_SIGN_IN_URL
if 'hkticketing.com' in homepage:
if len(config_dict["advanced"]["hkticketing_account"])>0:
homepage = CONST_HKTICKETING_SIGN_IN_URL
if 'ticketplus.com.tw' in homepage:
if len(config_dict["advanced"]["ticketplus_account"]) > 1:
homepage = "https://ticketplus.com.tw/"
print("goto url:", homepage)
driver.get(homepage)
time.sleep(3.0)
tixcraft_family = False
if 'tixcraft.com' in homepage:
tixcraft_family = True
if 'indievox.com' in homepage:
tixcraft_family = True
if 'ticketmaster.' in homepage:
tixcraft_family = True
if tixcraft_family:
tixcraft_sid = config_dict["advanced"]["tixcraft_sid"]
if len(tixcraft_sid) > 1:
driver.delete_cookie("SID")
driver.add_cookie({"name":"SID", "value": tixcraft_sid, "path" : "/", "secure":True})
if 'ibon.com' in homepage:
ibonqware = config_dict["advanced"]["ibonqware"]
if len(ibonqware) > 1:
driver.delete_cookie("ibonqware")
driver.add_cookie({"name":"ibonqware", "value": ibonqware, "domain" : "ibon.com.tw", "secure":True})
except WebDriverException as exce2:
print('oh no not again, WebDriverException')
print('WebDriverException:', exce2)
except Exception as exce1:
print('get URL Exception:', exce1)
pass
return driver
def force_press_button_iframe(driver, f, select_by, select_query, force_submit=True):
if not f:
# ensure we are on main content frame
try:
driver.switch_to.default_content()
except Exception as exc:
pass
else:
try:
driver.switch_to.frame(f)
except Exception as exc:
pass
is_clicked = press_button(driver, select_by, select_query, force_submit)
if f:
# switch back to main content, otherwise we will get StaleElementReferenceException
try:
driver.switch_to.default_content()
except Exception as exc:
pass
return is_clicked
def remove_attribute_tag_by_selector(driver, select_query, class_name, more_script = ""):
element_script = "eachItem.removeAttribute('"+ class_name +"');"
javascript_tag_by_selector(driver, select_query, element_script, more_script = more_script)
def remove_class_tag_by_selector(driver, select_query, class_name, more_script = ""):
element_script = "eachItem.classList.remove('"+ class_name +"');"
javascript_tag_by_selector(driver, select_query, element_script, more_script = more_script)
def hide_tag_by_selector(driver, select_query, more_script = ""):
element_script = "eachItem.style='display:none;';"
javascript_tag_by_selector(driver, select_query, element_script, more_script = more_script)
def clean_tag_by_selector(driver, select_query, more_script = ""):
element_script = "eachItem.outerHTML='';"
javascript_tag_by_selector(driver, select_query, element_script, more_script = more_script)
# PS: selector query string must without single quota.
def javascript_tag_by_selector(driver, select_query, element_script, more_script = ""):
try:
driver.set_script_timeout(1)
js = """var selectSoldoutItems = document.querySelectorAll('%s');
selectSoldoutItems.forEach((eachItem) =>
{%s});
%s""" % (select_query, element_script, more_script)
#print("javascript:", js)
driver.execute_script(js)
ret = True
except Exception as exc:
#print(exc)
pass
def press_button(driver, select_by, select_query, force_submit=True):
ret = False
next_step_button = None
try:
next_step_button = driver.find_element(select_by ,select_query)
if not next_step_button is None:
if next_step_button.is_enabled():
next_step_button.click()
ret = True
except Exception as exc:
#print("find %s clickable Exception:" % (select_query))
#print(exc)
pass
if force_submit:
if not next_step_button is None:
is_visible = False
try:
if next_step_button.is_enabled():
is_visible = True
except Exception as exc:
pass
if is_visible:
try:
driver.set_script_timeout(1)
driver.execute_script("arguments[0].click();", next_step_button)
ret = True
except Exception as exc:
pass
return ret
# close some div on home url.
def tixcraft_home_close_window(driver):
accept_all_cookies_btn = None
try:
accept_all_cookies_btn = driver.find_element(By.CSS_SELECTOR, '#onetrust-accept-btn-handler')
if accept_all_cookies_btn:
accept_all_cookies_btn.click()
except Exception as exc:
#print(exc)
pass
# from detail to game
def tixcraft_redirect(driver, url):
ret = False
game_name = ""
url_split = url.split("/")
if len(url_split) >= 6:
game_name = url_split[5]
if len(game_name) > 0:
if "/activity/detail/%s" % (game_name,) in url:
entry_url = url.replace("/activity/detail/","/activity/game/")
print("redirec to new url:", entry_url)
try:
driver.get(entry_url)
ret = True
except Exception as exec1:
pass
return ret
def tixcraft_date_auto_select(driver, url, config_dict, domain_name):
show_debug_message = True # debug.
show_debug_message = False # online
if config_dict["advanced"]["verbose"]:
show_debug_message = True
# read config.
auto_select_mode = config_dict["date_auto_select"]["mode"]
date_keyword = config_dict["date_auto_select"]["date_keyword"].strip()
pass_date_is_sold_out_enable = config_dict["tixcraft"]["pass_date_is_sold_out"]
auto_reload_coming_soon_page_enable = config_dict["tixcraft"]["auto_reload_coming_soon_page"]
# PS: for big events, check sold out text maybe not helpful, due to database is too busy.
sold_out_text_list = ["選購一空","已售完","No tickets available","Sold out","空席なし","完売した"]
# PS: "Start ordering" for indievox.com.