-
Notifications
You must be signed in to change notification settings - Fork 36
/
interpark_bot.py
2202 lines (1844 loc) · 75.7 KB
/
interpark_bot.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
import json
import logging
import os
import pathlib
import platform
import random
import sys
import time
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
logging.basicConfig()
logger = logging.getLogger('logger')
import warnings
from urllib3.exceptions import InsecureRequestWarning
warnings.simplefilter('ignore',InsecureRequestWarning)
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# ocr
import base64
try:
import ddddocr
from NonBrowser import NonBrowser
except Exception as exc:
pass
import argparse
import chromedriver_autoinstaller
CONST_APP_VERSION = "Max Interpark Bot (2023.09.02)"
CONST_MAXBOT_CONFIG_FILE = 'settings.json'
CONST_MAXBOT_LAST_URL_FILE = "MAXBOT_LAST_URL.txt"
CONST_MAXBOT_INT28_FILE = "MAXBOT_INT28_IDLE.txt"
CONST_HOMEPAGE_DEFAULT = "https://www.globalinterpark.com/"
CONST_INTERPARK_SIGN_IN_URL = "https://www.globalinterpark.com/user/signin"
CONST_CHROME_VERSION_NOT_MATCH_EN="Please download the WebDriver version to match your browser version."
CONST_CHROME_VERSION_NOT_MATCH_TW="請下載與您瀏覽器相同版本的WebDriver版本,或更新您的瀏覽器版本。"
CONST_FROM_TOP_TO_BOTTOM = u"from top to bottom"
CONST_FROM_BOTTOM_TO_TOP = u"from bottom to top"
CONST_RANDOM = u"random"
CONST_SELECT_ORDER_DEFAULT = CONST_FROM_TOP_TO_BOTTOM
CONST_WEBDRIVER_TYPE_SELENIUM = "selenium"
CONST_WEBDRIVER_TYPE_UC = "undetected_chromedriver"
def t_or_f(arg):
ret = False
ua = str(arg).upper()
if 'TRUE'.startswith(ua):
ret = True
elif 'YES'.startswith(ua):
ret = True
return ret
def sx(s1):
key=18
return ''.join(chr(ord(a) ^ key) for a in s1)
def decryptMe(b):
s=""
if(len(b)>0):
s=sx(base64.b64decode(b).decode("UTF-8"))
return s
def encryptMe(s):
data=""
if(len(s)>0):
data=base64.b64encode(sx(s).encode('UTF-8')).decode("UTF-8")
return data
def get_app_root():
# 讀取檔案裡的參數值
basis = ""
if hasattr(sys, 'frozen'):
basis = sys.executable
else:
basis = sys.argv[0]
app_root = os.path.dirname(basis)
return app_root
def get_config_dict(args):
app_root = 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):
with open(config_filepath) as json_data:
config_dict = json.load(json_data)
return config_dict
def write_last_url_to_file(url):
outfile = None
if platform.system() == 'Windows':
outfile = open(CONST_MAXBOT_LAST_URL_FILE, 'w', encoding='UTF-8')
else:
outfile = open(CONST_MAXBOT_LAST_URL_FILE, 'w')
if not outfile is None:
outfile.write("%s" % 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):
print("webdriver_path:", webdriver_path)
extension_list = []
extension_list.append(os.path.join(webdriver_path,"Adblock_3.18.1.0.crx"))
extension_list.append(os.path.join(webdriver_path,"Buster_2.0.1.0.crx"))
extension_list.append(os.path.join(webdriver_path,"no_google_analytics_1.1.0.0.crx"))
extension_list.append(os.path.join(webdriver_path,"proxy-switchyomega_2.5.21.0.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_brave_bin_path():
brave_path = ""
if platform.system() == 'Windows':
brave_path = "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
if not os.path.exists(brave_path):
brave_path = os.path.expanduser('~') + "\\AppData\\Local\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
if not os.path.exists(brave_path):
brave_path = "C:\\Program Files (x86)\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
if not os.path.exists(brave_path):
brave_path = "D:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
if platform.system() == 'Linux':
brave_path = "/usr/bin/brave-browser"
if platform.system() == 'Darwin':
brave_path = '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'
return brave_path
def get_chrome_options(webdriver_path, adblock_plus_enable, browser="chrome", headless = False):
chrome_options = webdriver.ChromeOptions()
if browser=="edge":
chrome_options = webdriver.EdgeOptions()
if browser=="safari":
chrome_options = webdriver.SafariOptions()
# some windows cause: timed out receiving message from renderer
if adblock_plus_enable:
# PS: this is ocx version.
extension_list = get_favoriate_extension_path(webdriver_path)
for ext in extension_list:
if os.path.exists(ext):
chrome_options.add_extension(ext)
if headless:
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('--disable-features=TranslateUI')
chrome_options.add_argument('--disable-translate')
chrome_options.add_argument('--lang=zh-TW')
chrome_options.add_argument('--disable-web-security')
chrome_options.add_argument("--no-sandbox");
chrome_options.add_argument("--disable-popup-blocking")
chrome_options.add_argument("--disable-notifications")
# 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", {"credentials_enable_service": False, "profile.password_manager_enabled": False, "translate":{"enabled": False}})
if browser=="brave":
brave_path = 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 = 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.install(path=webdriver_path, make_version_dir=False)
else:
print("ChromeDriver exist:", chromedriver_path)
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(URL_CHROME_DRIVER)
else:
chrome_service = Service(chromedriver_path)
chrome_options = get_chrome_options(webdriver_path, config_dict["advanced"]["adblock_plus_enable"], browser=config_dict["browser"], headless=config_dict["advanced"]["headless"])
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.install(path=webdriver_path, make_version_dir=False)
chrome_service = Service(chromedriver_path)
try:
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:
driver = webdriver.Chrome(service=Service(), options=chrome_options)
except Exception as exc3:
print(exc3)
pass
if driver_type=="stealth":
from selenium_stealth import stealth
# Selenium Stealth settings
stealth(driver,
languages=["zh-TW", "zh"],
vendor="Google Inc.",
platform="Win32",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
)
#print("driver capabilities", driver.capabilities)
return driver
def clean_uc_exe_cache():
exe_name = "chromedriver%s"
platform = sys.platform
if platform.endswith("win32"):
exe_name %= ".exe"
if platform.endswith(("linux", "linux2")):
exe_name %= ""
if platform.endswith("darwin"):
exe_name %= ""
d = ""
if platform.endswith("win32"):
d = "~/appdata/roaming/undetected_chromedriver"
elif "LAMBDA_TASK_ROOT" in os.environ:
d = "/tmp/undetected_chromedriver"
elif platform.startswith(("linux", "linux2")):
d = "~/.local/share/undetected_chromedriver"
elif platform.endswith("darwin"):
d = "~/Library/Application Support/undetected_chromedriver"
else:
d = "~/.undetected_chromedriver"
data_path = os.path.abspath(os.path.expanduser(d))
is_cache_exist = False
p = pathlib.Path(data_path)
files = list(p.rglob("*chromedriver*?"))
for file in files:
if os.path.exists(str(file)):
is_cache_exist = True
try:
os.unlink(str(file))
except Exception as exc2:
print(exc2)
pass
return is_cache_exist
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 = 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)
chromedriver_autoinstaller.install(path=webdriver_path, make_version_dir=False)
else:
print("ChromeDriver exist:", chromedriver_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)
if config_dict["advanced"]["adblock_plus_enable"]:
load_extension_path = ""
extension_list = get_favoriate_extension_path(webdriver_path)
for ext in extension_list:
ext = ext.replace('.crx','')
if os.path.exists(ext):
load_extension_path += ("," + os.path.abspath(ext))
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('--disable-features=TranslateUI')
options.add_argument('--disable-translate')
options.add_argument('--lang=zh-TW')
options.add_argument('--disable-web-security')
options.add_argument("--no-sandbox");
options.add_argument("--disable-popup-blocking")
options.add_argument("--disable-notifications")
options.add_argument("--password-store=basic")
options.add_experimental_option("prefs", {"credentials_enable_service": False, "profile.password_manager_enabled": False, "translate":{"enabled": False}})
if config_dict["browser"]=="brave":
brave_path = get_brave_bin_path()
if os.path.exists(brave_path):
options.binary_location = brave_path
driver = None
if os.path.exists(chromedriver_path):
# use chromedriver_autodownload instead of uc auto download.
is_cache_exist = clean_uc_exe_cache()
try:
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)
# 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.install(path=webdriver_path, make_version_dir=False)
try:
driver = uc.Chrome(driver_executable_path=chromedriver_path, options=options, headless=config_dict["advanced"]["headless"])
except Exception as exc2:
pass
else:
print("WebDriver not found at path:", chromedriver_path)
if driver is None:
print('WebDriver object is None..., try again..')
try:
driver = uc.Chrome(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)
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):
global driver
# read config.
homepage = config_dict["homepage"]
if not config_dict is None:
# output config:
print("maxbot app version", CONST_APP_VERSION)
print("python version", platform.python_version())
print("homepage", config_dict["homepage"])
homepage = config_dict["homepage"]
# entry point
if homepage is None:
homepage = ""
if len(homepage) == 0:
homepage = CONST_HOMEPAGE_DEFAULT
Root_Dir = 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_UC:
driver = load_chromdriver_normal(config_dict, config_dict["webdriver_type"])
else:
# 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["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["advanced"]["adblock_plus_enable"], browser="edge", headless=config_dict["advanced"]["headless"])
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:
print("goto url:", homepage)
if 'globalinterpark.com' in homepage:
if len(config_dict["advanced"]["interpark_account"])>0:
homepage = CONST_INTERPARK_SIGN_IN_URL
driver.get(homepage)
time.sleep(3.0)
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 get_current_url(driver):
DISCONNECTED_MSG = ': target window already closed'
url = ""
is_quit_bot = False
try:
url = driver.current_url
except NoSuchWindowException:
print('NoSuchWindowException at this url:', url )
#print("last_url:", last_url)
#print("get_log:", driver.get_log('driver'))
window_handles_count = 0
try:
window_handles_count = len(driver.window_handles)
#print("window_handles_count:", window_handles_count)
if window_handles_count >= 1:
driver.switch_to.window(driver.window_handles[0])
driver.switch_to.default_content()
time.sleep(0.2)
except Exception as excSwithFail:
#print("excSwithFail:", excSwithFail)
pass
if window_handles_count==0:
try:
driver_log = driver.get_log('driver')[-1]['message']
print("get_log:", driver_log)
if DISCONNECTED_MSG in driver_log:
print('quit bot by NoSuchWindowException')
is_quit_bot = True
driver.quit()
sys.exit()
except Exception as excGetDriverMessageFail:
#print("excGetDriverMessageFail:", excGetDriverMessageFail)
except_string = str(excGetDriverMessageFail)
if 'HTTP method not allowed' in except_string:
print('quit bot by close browser')
is_quit_bot = True
driver.quit()
sys.exit()
except UnexpectedAlertPresentException as exc1:
print('UnexpectedAlertPresentException at this url:', url )
# PS: do nothing...
# PS: current chrome-driver + chrome call current_url cause alert/prompt dialog disappear!
# raise exception at selenium/webdriver/remote/errorhandler.py
# after dialog disappear new excpetion: unhandled inspector error: Not attached to an active page
is_pass_alert = False
is_pass_alert = True
if is_pass_alert:
try:
driver.switch_to.alert.accept()
except Exception as exc:
pass
except Exception as exc:
logger.error('Maxbot URL Exception')
logger.error(exc, exc_info=True)
#UnicodeEncodeError: 'ascii' codec can't encode characters in position 63-72: ordinal not in range(128)
str_exc = ""
try:
str_exc = str(exc)
except Exception as exc2:
pass
if len(str_exc)==0:
str_exc = repr(exc)
exit_bot_error_strings = ['Max retries exceeded'
, 'chrome not reachable'
, 'unable to connect to renderer'
, 'failed to check if window was closed'
, 'Failed to establish a new connection'
, 'Connection refused'
, 'disconnected'
, 'without establishing a connection'
, 'web view not found'
, 'invalid session id'
]
for each_error_string in exit_bot_error_strings:
if isinstance(str_exc, str):
if each_error_string in str_exc:
print('quit bot by error:', each_error_string)
is_quit_bot = True
driver.quit()
sys.exit()
# not is above case, print exception.
print("Exception:", str_exc)
pass
return url, is_quit_bot
def format_keyword_string(keyword):
if not keyword is None:
if len(keyword) > 0:
keyword = keyword.replace('/','/')
keyword = keyword.replace(' ','')
keyword = keyword.replace(',','')
keyword = keyword.replace(',','')
keyword = keyword.replace('$','')
keyword = keyword.replace(' ','').lower()
return keyword
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 = force_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 check_checkbox(driver, by, query):
show_debug_message = True # debug.
show_debug_message = False # online
agree_checkbox = None
try:
agree_checkbox = driver.find_element(by, query)
except Exception as exc:
if show_debug_message:
print(exc)
pass
is_checkbox_checked = False
if agree_checkbox is not None:
is_checkbox_checked = force_check_checkbox(driver, agree_checkbox)
return is_checkbox_checked
def force_check_checkbox(driver, agree_checkbox):
is_finish_checkbox_click = False
if agree_checkbox is not None:
is_visible = False
try:
if agree_checkbox.is_enabled():
is_visible = True
except Exception as exc:
pass
if is_visible:
is_checkbox_checked = False
try:
if agree_checkbox.is_selected():
is_checkbox_checked = True
except Exception as exc:
pass
if not is_checkbox_checked:
#print('send check to checkbox')
try:
agree_checkbox.click()
is_finish_checkbox_click = True
except Exception as exc:
try:
driver.execute_script("arguments[0].click();", agree_checkbox)
is_finish_checkbox_click = True
except Exception as exc:
pass
else:
is_finish_checkbox_click = True
return is_finish_checkbox_click
def force_press_button(driver, select_by, select_query, force_submit=True):
is_clicked = 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()
is_clicked = 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)
is_clicked = True
except Exception as exc:
pass
return is_clicked
def assign_select_by_text(driver, by, query, val):
show_debug_message = True # debug.
show_debug_message = False # online
if val is None:
val = ""
is_text_sent = False
if len(val) > 0:
el_text = None
try:
el_text = driver.find_element(by, query)
except Exception as exc:
if show_debug_message:
print(exc)
pass
select_obj = None
if el_text is not None:
try:
if el_text.is_enabled() and el_text.is_displayed():
select_obj = Select(el_text)
if not select_obj is None:
select_obj.select_by_visible_text(val)
is_text_sent = True
except Exception as exc:
if show_debug_message:
print(exc)
pass
return is_text_sent
def assign_text(driver, by, query, val, overwrite = False, submit=False):
show_debug_message = True # debug.
show_debug_message = False # online
if val is None:
val = ""
is_visible = False
if len(val) > 0:
el_text = None
try:
el_text = driver.find_element(by, query)
except Exception as exc:
if show_debug_message:
print(exc)
pass
if el_text is not None:
try:
if el_text.is_enabled() and el_text.is_displayed():
is_visible = True
except Exception as exc:
if show_debug_message:
print(exc)
pass
is_text_sent = False
if is_visible:
try:
inputed_text = el_text.get_attribute('value')
if inputed_text is not None:
is_do_keyin = False
if len(inputed_text) == 0:
is_do_keyin = True
else:
if inputed_text == val:
is_text_sent = True
else:
if overwrite:
el_text.clear()
is_do_keyin = True
if is_do_keyin:
el_text.click()
el_text.send_keys(val)
if submit:
el_text.send_keys(Keys.ENTER)
is_text_sent = True
except Exception as exc:
if show_debug_message:
print(exc)
pass
return is_text_sent
def facebook_login(driver, account, password):
is_email_sent = assign_text(driver, By.CSS_SELECTOR, '#email', account)
is_password_sent = False
if is_email_sent:
is_password_sent = assign_text(driver, By.CSS_SELECTOR, '#pass', password, submit=True)
return is_password_sent
def interpark_get_local_code(locale_title):
code = "en"
if locale_title == "한국어":
code = "ko"
if locale_title == "中文":
code = "zh-cn"
if locale_title == "日本語":
code = "ja"
return code
def interpark_change_locale(driver, config_dict, url):
el_locale = None
try:
el_locale = driver.find_element(By.CSS_SELECTOR, 'body > main > nav > div > ul > li:nth-child(4) > div > div')
current_locale = el_locale.text
if len(current_locale) > 0:
if config_dict["locale"] != current_locale:
local_code = interpark_get_local_code(config_dict["locale"])
new_url = "https://www.globalinterpark.com/login?lang=" + local_code
if new_url != url:
driver.get(new_url)
except Exception as exc:
print(exc)
pass
interpark_account = config_dict["advanced"]["interpark_account"]
if len(interpark_account) > 2:
interpark_login(driver, interpark_account, decryptMe(config_dict["advanced"]["interpark_password"]))
def search_iframe(driver, f, by, value):
elem = None
if not f:
# ensure we are on main content frame
try:
driver.switch_to.default_content()
elem = driver.find_elements(by, value)
except Exception as exc:
pass
else:
try:
driver.switch_to.frame(f)
elem = driver.find_elements(by, value)
except Exception as exc:
print(exc)
pass
# switch back to main content, otherwise we will get StaleElementReferenceException
try:
driver.switch_to.default_content()
except Exception as exc:
pass
return elem
def get_matched_blocks_by_keyword_item_set(config_dict, auto_select_mode, keyword_item_set, formated_area_list):
show_debug_message = True # debug.
show_debug_message = False # online
if config_dict["advanced"]["verbose"]:
show_debug_message = True
matched_blocks = []
for row in formated_area_list:
row_text = ""
try:
row_text = row.text
except Exception as exc:
pass
if row_text is None:
row_text = ""
if len(row_text) > 0:
if reset_row_text_if_match_keyword_exclude(config_dict, row_text):
row_text = ""
if len(row_text) > 0:
if show_debug_message:
print("row_text:", row_text)
is_match_all = False
if ' ' in keyword_item_set:
keyword_item_array = keyword_item_set.split(' ')
is_match_all = True
for keyword_item in keyword_item_array:
keyword_item = format_keyword_string(keyword_item)
if not keyword_item in row_text:
is_match_all = False
else:
exclude_item = format_keyword_string(keyword_item_set)
if exclude_item in row_text:
is_match_all = True
if is_match_all:
matched_blocks.append(row)
# only need first row.
if auto_select_mode == CONST_FROM_TOP_TO_BOTTOM:
break
return matched_blocks