-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb_actions.py
1862 lines (1638 loc) · 84.7 KB
/
web_actions.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
import atexit
import traceback
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import ElementClickInterceptedException, InvalidSelectorException
from selenium.webdriver.remote.webelement import WebElement
from enum import Enum
from typing import List, Optional, Any, Dict, Union
import re
import time
try:
from tqdm import tqdm
tqdm_installed = True
except ImportError:
tqdm_installed = False
try:
import undetected_chromedriver as uc
uc_installed = True
except ImportError:
uc_installed = False
class SelectorType(Enum):
XPATH = "xpath"
CSS = "css selector"
ID = "id"
NAME = "name"
CLASS_NAME = "class name"
TAG_NAME = "tag name"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
def clean_traceback(tb: str) -> str:
"""
Clean the traceback by removing unhelpful parts and add a divider.
Args:
tb (str): The original traceback string.
Returns:
str: The cleaned traceback string.
"""
lines = tb.splitlines()
cleaned_lines = ["-----------------------"]
stacktrace_found = False
for line in lines:
if stacktrace_found:
if re.match(r"#\d+\s0x[0-9a-fA-F]+", line.strip()):
continue
else:
stacktrace_found = False # Stop skipping lines once we encounter a non-matching line
if "Stacktrace:" in line:
stacktrace_found = True
continue # Skip the "Stacktrace:" line itself
cleaned_lines.append(line)
return "\n".join(cleaned_lines)
def format_deeper_traceback() -> str:
"""
Format a deeper traceback by combining the current stack trace with the exception traceback.
Returns:
str: The formatted deeper traceback string.
"""
current_stack = traceback.format_stack()[:-1] # Exclude the current function call
exception_traceback = traceback.format_exc().splitlines()
combined_traceback = current_stack + exception_traceback
return "\n".join(combined_traceback)
class WebSession:
def __init__(self, options: Optional[Dict[str, Any]] = None, use_undetected: bool = False) -> None:
"""
Initialize the WebSession.
Args:
options (dict): A dictionary of options to configure the browser.
use_undetected (bool): Whether to use undetected ChromeDriver.
"""
chrome_options = webdriver.ChromeOptions()
if options:
for key, value in options.items():
# Ensure the key is prefixed with '--'
prefixed_key = key if key.startswith("--") else f"--{key}"
if isinstance(value, bool) and value:
chrome_options.add_argument(prefixed_key)
elif isinstance(value, str):
chrome_options.add_argument(f"{prefixed_key}={value}")
# Add more specific handling as needed
if use_undetected and uc_installed:
self.driver = uc.Chrome(options=chrome_options)
else:
self.driver = webdriver.Chrome(options=chrome_options)
atexit.register(self.close)
def __del__(self):
"""Clean up resources when the object is destroyed."""
try:
self.driver.quit()
except Exception:
pass
def close(self) -> bool:
"""
Close the browser session.
Returns:
bool: True if the session is successfully closed.
"""
if self.driver:
self.driver.quit()
return True
def debug(self) -> None:
"""
Open the browser and wait indefinitely for debugging purposes.
"""
print("Debug mode: Browser is open and waiting indefinitely.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Debug mode: Exiting on keyboard interrupt.")
finally:
self.close()
def wait_for_element(self, selector_type: SelectorType, selector: str, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> Optional[WebElement]:
"""
Wait for an element to be present in the DOM.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
timeout (int): The maximum time to wait for the element.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
WebElement: The found element, or None if not found.
"""
try:
if selector_type == SelectorType.XPATH:
return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located((By.XPATH, selector)))
elif selector_type == SelectorType.CSS:
return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return None
def wait_for_elements(self, selector_type: SelectorType, selector: str, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> List[WebElement]:
"""
Wait for multiple elements to be present in the DOM.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
timeout (int): The maximum time to wait for the elements.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
list: A list of found elements, or an empty list if none are found.
"""
try:
if selector_type == SelectorType.XPATH:
return WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located((By.XPATH, selector)))
elif selector_type == SelectorType.CSS:
return WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, selector)))
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return []
def find_element(self, selector_type: SelectorType, selector: str, element: Optional[WebElement] = None, suppress_traceback: bool = False, raise_exc: bool = False, timeout: int = None) -> Optional[WebElement]:
"""
Find a single element using various selector types with an optional timeout.
Args:
selector_type (SelectorType): The type of selector (XPATH, CSS, ID, NAME, CLASS_NAME, TAG_NAME, LINK_TEXT, PARTIAL_LINK_TEXT).
selector (str): The selector string.
element (WebElement): The WebElement object to search within.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
timeout (int): The time to wait for the element, if not given, no timeout will be used.
Returns:
WebElement: The found element, or None if not found.
"""
try:
if element:
if timeout:
wait = WebDriverWait(element, timeout)
if selector_type == SelectorType.XPATH:
return wait.until(EC.presence_of_element_located((By.XPATH, selector)))
elif selector_type == SelectorType.CSS:
return wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
elif selector_type == SelectorType.ID:
return wait.until(EC.presence_of_element_located((By.ID, selector)))
elif selector_type == SelectorType.NAME:
return wait.until(EC.presence_of_element_located((By.NAME, selector)))
elif selector_type == SelectorType.CLASS_NAME:
return wait.until(EC.presence_of_element_located((By.CLASS_NAME, selector)))
elif selector_type == SelectorType.TAG_NAME:
return wait.until(EC.presence_of_element_located((By.TAG_NAME, selector)))
elif selector_type == SelectorType.LINK_TEXT:
return wait.until(EC.presence_of_element_located((By.LINK_TEXT, selector)))
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, selector)))
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
else:
if selector_type == SelectorType.XPATH:
return element.find_element(By.XPATH, selector)
elif selector_type == SelectorType.CSS:
return element.find_element(By.CSS_SELECTOR, selector)
elif selector_type == SelectorType.ID:
return element.find_element(By.ID, selector)
elif selector_type == SelectorType.NAME:
return element.find_element(By.NAME, selector)
elif selector_type == SelectorType.CLASS_NAME:
return element.find_element(By.CLASS_NAME, selector)
elif selector_type == SelectorType.TAG_NAME:
return element.find_element(By.TAG_NAME, selector)
elif selector_type == SelectorType.LINK_TEXT:
return element.find_element(By.LINK_TEXT, selector)
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return element.find_element(By.PARTIAL_LINK_TEXT, selector)
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
else:
if timeout:
wait = WebDriverWait(self.driver, timeout)
if selector_type == SelectorType.XPATH:
return wait.until(EC.presence_of_element_located((By.XPATH, selector)))
elif selector_type == SelectorType.CSS:
return wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
elif selector_type == SelectorType.ID:
return wait.until(EC.presence_of_element_located((By.ID, selector)))
elif selector_type == SelectorType.NAME:
return wait.until(EC.presence_of_element_located((By.NAME, selector)))
elif selector_type == SelectorType.CLASS_NAME:
return wait.until(EC.presence_of_element_located((By.CLASS_NAME, selector)))
elif selector_type == SelectorType.TAG_NAME:
return wait.until(EC.presence_of_element_located((By.TAG_NAME, selector)))
elif selector_type == SelectorType.LINK_TEXT:
return wait.until(EC.presence_of_element_located((By.LINK_TEXT, selector)))
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, selector)))
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
else:
if selector_type == SelectorType.XPATH:
return self.driver.find_element(By.XPATH, selector)
elif selector_type == SelectorType.CSS:
return self.driver.find_element(By.CSS_SELECTOR, selector)
elif selector_type == SelectorType.ID:
return self.driver.find_element(By.ID, selector)
elif selector_type == SelectorType.NAME:
return self.driver.find_element(By.NAME, selector)
elif selector_type == SelectorType.CLASS_NAME:
return self.driver.find_element(By.CLASS_NAME, selector)
elif selector_type == SelectorType.TAG_NAME:
return self.driver.find_element(By.TAG_NAME, selector)
elif selector_type == SelectorType.LINK_TEXT:
return self.driver.find_element(By.LINK_TEXT, selector)
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return self.driver.find_element(By.PARTIAL_LINK_TEXT, selector)
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return None
def find_elements(self, selector_type: SelectorType, selector: str, element: Optional[WebElement] = None, suppress_traceback: bool = False, raise_exc: bool = False, timeout: int = None) -> List[WebElement]:
"""
Find elements using various selector types.
Args:
selector_type (SelectorType): The type of selector (XPATH, CSS, ID, NAME, CLASS_NAME, TAG_NAME, LINK_TEXT, PARTIAL_LINK_TEXT).
selector (str): The selector string.
element (WebElement): The WebElement object to search within.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
timeout (int): The time to wait for the elements, if not given, no timeout will be used
Returns:
list: A list of found elements, or an empty list if none are found.
"""
try:
if element:
if timeout:
wait = WebDriverWait(element, timeout)
if selector_type == SelectorType.XPATH:
return wait.until(EC.presence_of_all_elements_located((By.XPATH, selector)))
elif selector_type == SelectorType.CSS:
return wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, selector)))
elif selector_type == SelectorType.ID:
return wait.until(EC.presence_of_all_elements_located((By.ID, selector)))
elif selector_type == SelectorType.NAME:
return wait.until(EC.presence_of_all_elements_located((By.NAME, selector)))
elif selector_type == SelectorType.CLASS_NAME:
return wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, selector)))
elif selector_type == SelectorType.TAG_NAME:
return wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, selector)))
elif selector_type == SelectorType.LINK_TEXT:
return wait.until(EC.presence_of_all_elements_located((By.LINK_TEXT, selector)))
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return wait.until(EC.presence_of_all_elements_located((By.PARTIAL_LINK_TEXT, selector)))
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
else:
if selector_type == SelectorType.XPATH:
return element.find_elements(By.XPATH, selector)
elif selector_type == SelectorType.CSS:
return element.find_elements(By.CSS_SELECTOR, selector)
elif selector_type == SelectorType.ID:
return element.find_elements(By.ID, selector)
elif selector_type == SelectorType.NAME:
return element.find_elements(By.NAME, selector)
elif selector_type == SelectorType.CLASS_NAME:
return element.find_elements(By.CLASS_NAME, selector)
elif selector_type == SelectorType.TAG_NAME:
return element.find_elements(By.TAG_NAME, selector)
elif selector_type == SelectorType.LINK_TEXT:
return element.find_elements(By.LINK_TEXT, selector)
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return element.find_elements(By.PARTIAL_LINK_TEXT, selector)
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
else:
if timeout:
wait = WebDriverWait(self.driver, timeout)
if selector_type == SelectorType.XPATH:
return wait.until(EC.presence_of_all_elements_located((By.XPATH, selector)))
elif selector_type == SelectorType.CSS:
return wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, selector)))
elif selector_type == SelectorType.ID:
return wait.until(EC.presence_of_all_elements_located((By.ID, selector)))
elif selector_type == SelectorType.NAME:
return wait.until(EC.presence_of_all_elements_located((By.NAME, selector)))
elif selector_type == SelectorType.CLASS_NAME:
return wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, selector)))
elif selector_type == SelectorType.TAG_NAME:
return wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, selector)))
elif selector_type == SelectorType.LINK_TEXT:
return wait.until(EC.presence_of_all_elements_located((By.LINK_TEXT, selector)))
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return wait.until(EC.presence_of_all_elements_located((By.PARTIAL_LINK_TEXT, selector)))
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
else:
if selector_type == SelectorType.XPATH:
return self.driver.find_elements(By.XPATH, selector)
elif selector_type == SelectorType.CSS:
return self.driver.find_elements(By.CSS_SELECTOR, selector)
elif selector_type == SelectorType.ID:
return self.driver.find_elements(By.ID, selector)
elif selector_type == SelectorType.NAME:
return self.driver.find_elements(By.NAME, selector)
elif selector_type == SelectorType.CLASS_NAME:
return self.driver.find_elements(By.CLASS_NAME, selector)
elif selector_type == SelectorType.TAG_NAME:
return self.driver.find_elements(By.TAG_NAME, selector)
elif selector_type == SelectorType.LINK_TEXT:
return self.driver.find_elements(By.LINK_TEXT, selector)
elif selector_type == SelectorType.PARTIAL_LINK_TEXT:
return self.driver.find_elements(By.PARTIAL_LINK_TEXT, selector)
else:
raise ValueError(f"Unsupported selector type: {selector_type}")
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return []
def find_similar_elements(self, element: WebElement, similarity_criteria: str = "class", match_all_classes: bool = False, partial_match: bool = False, custom_xpath: Optional[str] = None, suppress_traceback: bool = False, reraise_exception: bool = False) -> List[WebElement]:
"""
Find similar elements in the DOM based on a given element and similarity criteria.
Args:
element (WebElement): The reference element to find similar elements.
similarity_criteria (str): The criteria for similarity ("tag", "class", "css_selector", "attribute"). Default is "class".
match_all_classes (bool): Whether to match all classes if similarity_criteria is "class".
partial_match (bool): Whether to allow partial matching for attributes.
custom_xpath (str): Custom XPath to use for finding similar elements.
suppress_traceback (bool): Whether to suppress the traceback print.
reraise_exception (bool): Whether to re-raise the exception.
Returns:
list: A list of similar elements, or an empty list if none are found.
"""
try:
if not element:
raise ValueError("Element must be provided.")
# Find the parent container that holds all similar elements
parent = element.find_element(By.XPATH, "..")
if custom_xpath:
similar_elements = parent.find_elements(By.XPATH, custom_xpath)
elif similarity_criteria == "tag":
similar_elements = parent.find_elements(By.XPATH, f".//{element.tag_name}")
elif similarity_criteria == "class":
class_names = element.get_attribute("class").split()
if not class_names:
return []
if match_all_classes:
class_condition = " and ".join([f"contains(@class, '{cls}')" for cls in class_names])
else:
class_condition = " or ".join([f"contains(@class, '{cls}')" for cls in class_names])
similar_elements = parent.find_elements(By.XPATH, f".//*[{class_condition}]")
elif similarity_criteria == "css_selector":
css_selector = self.get_css_selector(element)
similar_elements = parent.find_elements(By.CSS_SELECTOR, css_selector)
elif similarity_criteria.startswith("attribute:"):
attribute_name = similarity_criteria.split(":", 1)[1]
attribute_value = element.get_attribute(attribute_name)
if not attribute_value:
return []
if partial_match:
similar_elements = parent.find_elements(By.XPATH, f".//*[contains(@{attribute_name}, '{attribute_value}')]")
else:
similar_elements = parent.find_elements(By.XPATH, f".//*[@{attribute_name}='{attribute_value}']")
else:
raise ValueError(f"Unsupported similarity criteria: {similarity_criteria}")
# Filter out the reference element itself if it's included in the results
similar_elements = [el for el in similar_elements if el != element]
# Use a set to ensure no duplicates
unique_elements = []
seen = set()
for el in similar_elements:
el_id = el.get_attribute("id") or el.get_attribute("outerHTML")
if el_id not in seen:
seen.add(el_id)
unique_elements.append(el)
return unique_elements
except Exception:
if reraise_exception:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return []
def click(self, selector_type: SelectorType = None, selector: str = None, element: Optional[WebElement] = None, skip_wait: bool = False, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> bool:
"""
Click an element.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
skip_wait (bool): Whether to skip waiting for the element.
timeout (int): The maximum time to wait for the element.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
bool: True if the click is successful, False otherwise.
"""
try:
if not element and not selector_type and not selector:
raise ValueError("Element, selector_type, or selector must be provided.")
if not element:
element = self.find_element(selector_type, selector, skip_wait, timeout, suppress_traceback, raise_exc)
if element:
return element.click() #self.safe_click(element)
return False
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return False
def safe_click(self, element: WebElement, suppress_traceback: bool = False, raise_exc: bool = False) -> bool:
"""
Safely click an element, handling potential interceptors.
Args:
element (WebElement): The element to click.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
bool: True if the click is successful, False otherwise.
Note:
This method is experimental.
"""
try:
element.click()
return True
except ElementClickInterceptedException:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
# Find the element that intercepted the click
interceptor_element = self.driver.execute_script("""
var elem = arguments[0];
var rect = elem.getBoundingClientRect();
var x = rect.left + (rect.width / 2);
var y = rect.top + (rect.height / 2);
return document.elementFromPoint(x, y);
""", element)
if interceptor_element:
try:
print(f"Clicking interceptor element: {interceptor_element}")
interceptor_element.click()
return True
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return False
def right_click(self, selector_type: SelectorType, selector: str, skip_wait: bool = False, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> bool:
"""
Right-click an element.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
skip_wait (bool): Whether to skip waiting for the element.
timeout (int): The maximum time to wait for the element.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
bool: True if the right-click is successful, False otherwise.
"""
try:
element = self.find_element(selector_type, selector, skip_wait, timeout, suppress_traceback, raise_exc)
if element:
actions = ActionChains(self.driver)
actions.context_click(element).perform()
return True
return False
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return False
def type_text(self, selector_type: SelectorType, selector: str, text: str, skip_wait: bool = False, timeout: int = 10, interactable_timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> bool:
"""
Type text into an element.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
text (str): The text to type.
skip_wait (bool): Whether to skip waiting for the element.
timeout (int): The maximum time to wait for the element.
interactable_timeout (int): The maximum time to wait for the element to be interactable.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
bool: True if the text is successfully typed, False otherwise.
"""
try:
element = self.find_element(selector_type, selector, skip_wait, timeout, suppress_traceback, raise_exc)
if element:
if interactable_timeout != -1:
WebDriverWait(self.driver, interactable_timeout).until(EC.element_to_be_clickable((By.XPATH, selector)))
element.send_keys(text)
return True
return False
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return False
def clear(self, selector_type: SelectorType, selector: str, skip_wait: bool = False, timeout: int = 10, interactable_timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> bool:
"""
Clear the text in an element.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
skip_wait (bool): Whether to skip waiting for the element.
timeout (int): The maximum time to wait for the element.
interactable_timeout (int): The maximum time to wait for the element to be interactable.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
bool: True if the element is successfully cleared, False otherwise.
"""
try:
element = self.find_element(selector_type, selector, skip_wait, timeout, suppress_traceback, raise_exc)
if element:
if interactable_timeout != -1:
WebDriverWait(self.driver, interactable_timeout).until(EC.element_to_be_clickable((By.XPATH, selector)))
element.clear()
return True
return False
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return False
def hover(self, selector_type: SelectorType, selector: str, skip_wait: bool = False, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> bool:
"""
Hover over an element.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
skip_wait (bool): Whether to skip waiting for the element.
timeout (int): The maximum time to wait for the element.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
bool: True if the hover is successful, False otherwise.
"""
try:
element = self.find_element(selector_type, selector, skip_wait, timeout)
if element:
actions = ActionChains(self.driver)
actions.move_to_element(element).perform()
return True
return False
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return False
def extract(self, selector_type: Optional[SelectorType] = None, selector: Optional[str] = None, element: Optional[WebElement] = None, attribute: Optional[str] = None, skip_wait: bool = False, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> Optional[str]:
"""
Extract data from an element.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
element (WebElement): The WebElement object to extract data from.
attribute (str): The attribute to extract. Use "__text__" to extract the text content.
skip_wait (bool): Whether to skip waiting for the element.
timeout (int): The maximum time to wait for the element.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
str: The extracted data, or False if extraction does not succeed, and None if extraction errors.
"""
try:
sub_element = None
if element:
# If both element and selector/selector_type are provided, find the sub-element within the element
if selector_type and selector:
sub_element = self.find_element(selector_type, selector, element, suppress_traceback, raise_exc)
else:
sub_element = element
else:
# If only selector/selector_type are provided, find the element
sub_element = self.find_element(selector_type, selector, suppress_traceback=suppress_traceback, raise_exc=raise_exc)
if sub_element:
if attribute == "__text__":
return sub_element.text
elif attribute:
return sub_element.get_attribute(attribute)
else:
return sub_element.text
return False
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return None
def run_js(self, selector_type: SelectorType, selector: str, script: str, skip_wait: bool = False, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> Optional[Any]:
"""
Run JavaScript on an element.
Args:
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
script (str): The JavaScript code to run.
skip_wait (bool): Whether to skip waiting for the element.
timeout (int): The maximum time to wait for the element.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
Any: The result of the JavaScript execution, or None if execution fails.
"""
try:
element = self.find_element(selector_type, selector, skip_wait, timeout)
if element:
result = self.driver.execute_script(script, element)
print(f"JavaScript execution result: {result}")
return result
return None
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return None
def get_page_title(self, suppress_traceback: bool = False, raise_exc: bool = False) -> Optional[str]:
"""
Get the title of the page.
Returns:
str: The page title, or None if retrieval fails.
"""
try:
return self.driver.title
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return None
def get_page_source(self, suppress_traceback: bool = False, raise_exc: bool = False) -> Optional[str]:
"""
Get the source code of the page.
Returns:
str: The page source, or None if retrieval fails.
"""
try:
return self.driver.page_source
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return None
def get_current_url(self, suppress_traceback: bool = False, raise_exc: bool = False) -> Optional[str]:
"""
Get the current URL of the page.
Returns:
str: The current URL, or None if retrieval fails.
"""
try:
return self.driver.current_url
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return None
def scroll(self, direction: str = "down", amount: Optional[int] = None, selector_type: Optional[SelectorType] = None, selector: Optional[str] = None, element: Optional[WebElement] = None, x: Optional[int] = None, y: Optional[int] = None, to_end: bool = False, timeout: int = 10, suppress_traceback: bool = False, raise_exc: bool = False) -> bool:
"""
Scroll the page or an element.
Args:
direction (str): The direction to scroll ("down", "up", "to_element").
amount (int): The amount to scroll (used for "down" and "up" directions).
selector_type (SelectorType): The type of selector (XPATH or CSS) for the element to scroll to.
selector (str): The selector string for the element to scroll to.
element (WebElement): The WebElement object to scroll.
x (int): The x-coordinate to scroll to.
y (int): The y-coordinate to scroll to.
to_end (bool): If True, scrolls to the bottom of the element or the entire page. If False, scrolls to the top.
timeout (int): The maximum time to wait for the element.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
Returns:
bool: True if the scroll is successful, False otherwise.
"""
try:
if x is not None and y is not None:
self.driver.execute_script(f"window.scrollTo({x}, {y});")
elif direction == "down":
if amount:
self.driver.execute_script(f"window.scrollBy(0, {amount});")
elif element:
if to_end:
self.driver.execute_script("arguments[0].scrollIntoView(false);", element)
else:
self.driver.execute_script("arguments[0].scrollIntoView();", element)
elif selector_type and selector:
element = self.find_element(selector_type, selector, timeout=timeout, suppress_traceback=suppress_traceback, raise_exc=raise_exc)
if element:
if to_end:
self.driver.execute_script("arguments[0].scrollIntoView(false);", element)
else:
self.driver.execute_script("arguments[0].scrollIntoView();", element)
else:
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
elif direction == "up":
if amount:
self.driver.execute_script(f"window.scrollBy(0, -{amount});")
elif element:
if to_end:
self.driver.execute_script("arguments[0].scrollIntoView(true);", element)
else:
self.driver.execute_script("arguments[0].scrollIntoView();", element)
elif selector_type and selector:
element = self.find_element(selector_type, selector, timeout=timeout, suppress_traceback=suppress_traceback, raise_exc=raise_exc)
if element:
if to_end:
self.driver.execute_script("arguments[0].scrollIntoView(true);", element)
else:
self.driver.execute_script("arguments[0].scrollIntoView();", element)
else:
self.driver.execute_script("window.scrollTo(0, 0);")
elif direction == "to_element":
if element:
self.driver.execute_script("arguments[0].scrollIntoView();", element)
elif selector_type and selector:
element = self.find_element(selector_type, selector, timeout=timeout, suppress_traceback=suppress_traceback, raise_exc=raise_exc)
if element:
self.driver.execute_script("arguments[0].scrollIntoView();", element)
else:
raise ValueError("Invalid scroll parameters")
return True
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
return False
def go_to(self, url: str, suppress_traceback: bool = False, raise_exc: bool = False, return_status: bool = False) -> Optional[bool]:
"""
Navigate to a URL and optionally check if the page loaded successfully.
Args:
url (str): The URL to navigate to.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
return_status (bool): Whether to return the page load status using document.readyState.
Returns:
bool: True if the page loaded successfully, False otherwise. Returns None if return_status is False.
"""
try:
self.driver.get(url)
if return_status:
# Check if the document is fully loaded
ready_state = self.driver.execute_script("return document.readyState")
return ready_state == "complete"
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
if return_status:
return False
return None
def refresh(self, suppress_traceback: bool = False, raise_exc: bool = False) -> None:
"""
Refresh the current page.
Args:
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
"""
try:
self.driver.refresh()
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
def back(self, suppress_traceback: bool = False, raise_exc: bool = False) -> None:
"""
Navigate back in the browser history.
Args:
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
"""
try:
self.driver.back()
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
def forward(self, suppress_traceback: bool = False, raise_exc: bool = False) -> None:
"""
Navigate forward in the browser history.
Args:
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
"""
try:
self.driver.forward()
except Exception:
if raise_exc:
raise
if not suppress_traceback:
error_traceback = format_deeper_traceback()
print(clean_traceback(error_traceback))
def show_structure(self, element: Optional[WebElement] = None, selector_type: Optional[SelectorType] = None, selector: Optional[str] = None, indent: int = 0, suppress_traceback: bool = False, raise_exc: bool = False, save_to_file: bool = False, file_path: str = "structure_output.html") -> None:
"""
Recursively print the structure of the DOM starting from the given element or selector.
Args:
element (WebElement): The root element to start the structure display.
selector_type (SelectorType): The type of selector (XPATH or CSS).
selector (str): The selector string.
indent (int): The current indentation level for nested elements.
suppress_traceback (bool): Whether to suppress the traceback print.
raise_exc (bool): Whether to re-raise the exception.
save_to_file (bool): Whether to save the output to a file.
file_path (str): The file path to save the output if save_to_file is True.
"""
try:
output = []
def _show_structure(element, indent):
indent_str = ' ' * (indent * 2)
tag_name = element.tag_name
attributes = ' '.join([f'{attr["name"]}="{attr["value"]}"' for attr in element.get_property('attributes')])
text = element.text.strip()
line = f"{indent_str}<{tag_name} {attributes}> {text}"
output.append(line)
print(line)
children = element.find_elements(By.XPATH, './*')
for child in children:
_show_structure(child, indent + 1)
# Determine the root element to start from
if element and selector_type and selector:
if selector_type == SelectorType.XPATH:
root_element = element.find_element(By.XPATH, selector)
elif selector_type == SelectorType.CSS:
root_element = element.find_element(By.CSS_SELECTOR, selector)
else:
raise ValueError(f"Unsupported selector type: {selector_type}")